惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Jina AI
Jina AI
博客园 - 司徒正美
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
J
Java Code Geeks
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
爱范儿
爱范儿
美团技术团队
腾讯CDC
博客园 - Franky
MyScale Blog
MyScale Blog
人人都是产品经理
人人都是产品经理
罗磊的独立博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
aimingoo的专栏
aimingoo的专栏
博客园_首页
V
V2EX
Martin Fowler
Martin Fowler
T
The Blog of Author Tim Ferriss

博客园 - 可可

广东电信最新DNS更新了 分布式缓存失效处理 序列化 suse中计划任务工具cron的使用 转载《.NET框架设计之五------------异常设计(异常与返回值)》 《高级Bash脚本编程指南》在线阅读 转载《Linux Shell Bash 各种小技巧》 转载《Adding a Second IP Address to an Existing Network Adapter on Linux》 SuSE下chkconfig的启动脚本参考例子"/etc/init.d/skeleton” - 可可 - 博客园 转载《Starting and Stoping Services: insserv》 linux下c++程序编译错误--理解typename 一个公网IP情况下实现LVS VS/DR vmware中suse10不能上网解决方法 Using PHP with mod_fcgid Apache Configuration PHP在Apache中两种工作方式的区别(CGI模式、Apache 模块DLL) SSO 转贴《负载均衡技术介绍》 CDN
Linux多线程例子
可可 · 2009-06-21 · via 博客园 - 可可

//mutex.c

 #include <stdio.h>

#include<stdlib.h>

#include<unistd.h>

#include <pthread.h>

#include <string.h>

 void* reader_function(void *p);

 void* writer_function(void *p);

 char buffer[10]={0};

 int buffer_has_item=0;

 pthread_mutex_t mutex;

 int main(void)

 {

      pthread_t reader;

      pthread_mutex_init(&mutex,NULL);

      pthread_create(&reader,NULL, reader_function, NULL);

      writer_function(NULL);

 }

 void* writer_function(void *p)

 {

      int i,ti;

      for(i=1;i<3;)

      {

          ti=i;

          /* .....*/

          pthread_mutex_lock(&mutex);

          printf("Writer %d Locked Buffer.\r\n",i);

          if (buffer_has_item==0)

          {

              buffer_has_item=1;

              strcpy(buffer,"Full");

              printf("++Writer %d fill the buffer with context \"%s\".\r\n",i,buffer);

              i++;

          }

          /* .....*/

          printf("Writer %d Unlocked Buffer.\r\n\n\n",ti);

          pthread_mutex_unlock(&mutex);

          sleep(1);

      }

        return NULL;

 }

 void* reader_function(void *p)

 {

      int i,ti;

      for(i=1;i<3;)

      {

          ti=i;

          pthread_mutex_lock(&mutex);

          printf("Reader %d Locked Buffer.\r\n",i);

          if(buffer_has_item==1)

          {

              buffer_has_item=0;

              strcpy(buffer,"Empty");

              printf("--Reader %d clean the buffer with context \"%s\".\r\n",i,buffer);

              i++;

          }

          printf("Reader %d Unlocked Buffer.\r\n\n\n",ti);

          pthread_mutex_unlock(&mutex);

          sleep(1);

      }

        return NULL;

 }

编译命令:gcc -o mutex -lpthread -g mutex.c

执行./mutex