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

推荐订阅源

Y
Y Combinator Blog
GbyAI
GbyAI
U
Unit 42
WordPress大学
WordPress大学
Last Week in AI
Last Week in AI
P
Proofpoint News Feed
D
DataBreaches.Net
N
Netflix TechBlog - Medium
H
Hackread – Cybersecurity News, Data Breaches, AI and More
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
C
Check Point Blog
Martin Fowler
Martin Fowler
月光博客
月光博客
MongoDB | Blog
MongoDB | Blog
MyScale Blog
MyScale Blog
The Cloudflare Blog
Apple Machine Learning Research
Apple Machine Learning Research
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
M
MIT News - Artificial intelligence
云风的 BLOG
云风的 BLOG
罗磊的独立博客
B
Blog RSS Feed
J
Java Code Geeks
The GitHub Blog
The GitHub Blog

博客园 - 可可

广东电信最新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