源代码:

#include <stdio.h>

#include <pthread.h>

#include <sched.h>





void *producter_f (void *arg);

void *consumer_f (void *arg);









int buffer_has_item=0;

pthread_mutex_t mutex;





int running =1 ;





int main (void)

{

pthread_t consumer_t;

pthread_t producter_t;



pthread_mutex_init (&mutex,NULL);



pthread_create(&producter_t, NULL,(void*)producter_f, NULL );

pthread_create(&consumer_t, NULL, (void *)consumer_f, NULL);

usleep(1);

running =0;

pthread_join(consumer_t,NULL);

pthread_join(producter_t,NULL);

pthread_mutex_destroy(&mutex);



return 0;

}





void *producter_f (void *arg)

{

while(running)

{

pthread_mutex_lock (&mutex);

buffer_has_item++;

printf("生产,总数量:%d\n",buffer_has_item);

pthread_mutex_unlock(&mutex);

}

}





void *consumer_f(void *arg)

{

while(running)

{

pthread_mutex_lock(&mutex);

buffer_has_item--;


printf("消费,总数量:%d\n",buffer_has_item);

pthread_mutex_unlock(&mutex);

}

}

错误场景:

[root@luozhonghua 04]# gcc -o mutex ex04-5-mutex.c

/tmp/ccZuFiqr.o: In function `main':

ex04-5-mutex.c:(.text+0x3d): undefined reference to `pthread_create'

ex04-5-mutex.c:(.text+0x61): undefined reference to `pthread_create'

ex04-5-mutex.c:(.text+0x8b): undefined reference to `pthread_join'

ex04-5-mutex.c:(.text+0x9f): undefined reference to `pthread_join'

collect2: ld returned 1 exit status

分析:pthread 库不是 Linux 系统默认的库,连接时须要使用静态库 libpthread.a

处理:

在编译中加 -lpthread 參数

[root@luozhonghua 04]# gcc -lpthread -o mutex ex04-5-mutex.c

最新文章

  1. StatePattern
  2. j2ee servlet listener
  3. 分享:JS比较两个日期大小
  4. ios9 http请求失败的问题
  5. php 上传视频的代码
  6. BestCoder Round #36 (hdu5200)Strange Class(离线)
  7. Vim快捷键大全
  8. mysql 通过测试&#39;for update&#39;,深入了解行锁、表锁、索引
  9. PDF 补丁丁 0.6.0.3326 版发布(修复提取图片的问题)
  10. C# winform窗体间传值(使用委托或事件)
  11. HTML页面的重绘(repaint)和重流(reflow)
  12. mysql RR下不存在则插入
  13. php返回数组后处理(开户成功后弹窗提示)
  14. SDOI2018 二轮培训划水记
  15. RTMP(实时信息传输协议)详解
  16. 07.重写ToSting()方法
  17. python logging—模块
  18. CSS效果:图片切换
  19. 08_1_IO
  20. 初入IT行業,走出自我

热门文章

  1. 函数返回char* 的解决方案
  2. linux查看系统版本
  3. iOS之AFN错误代码1016(Error Domain=com.alamofire.error.serialization.response Code=-1016 &quot;Request failed: unacceptable)
  4. WEB 开发所用的网站
  5. java日期操作
  6. AJAX 跨域
  7. .net转php laraval框架学习系列(四) 项目实战---View
  8. 原生js和jquery实现图片轮播特效
  9. IOS 如何选择delegate、notification、KVO?
  10. matlab图像处理