建站优化

当前位置:

Linux下一个简单的多线程互斥锁的例子,linux多线程是怎么实现的

浏览量:108次

Linux下一个简单的多线程互斥锁的例子,linux多线程是怎么实现的

本篇文章是对Linux下一个简单的多线程互斥锁的例子进行了分析介绍,需要的朋友可以参考下

复制代码 代码如下:

#include #include pthread_mutex_t Device_mutex ; int count=0; void thread_func1() { while(1) { pthread_mutex_lock(&Device_mutex); printf("thread1: %dn",count); pthread_mutex_unlock(&Device_mutex); count++; sleep(1); } } void thread_func2() { while(1) { pthread_mutex_lock(&Device_mutex); printf("thread2: %dn",count); pthread_mutex_unlock(&Device_mutex); count++; sleep(1); } } int main() { pthread_t thread1, thread2; pthread_mutex_init(&Device_mutex,NULL); if(pthread_create(&thread1,NULL,(void*)thread_func1,NULL) == -1) { printf("create IP81 Thread error !n"); exit(1); } sleep(1); if(pthread_create(&thread2,NULL,(void *)thread_func2,NULL) == -1) { printf("create IP81_2 Thread error!n"); exit(1); } sleep(1); pthread_join(thread1,NULL); pthread_join(thread2,NULL); pthread_mutex_destroy(&Device_mutex); return 0; }

[声明]本网转载网络媒体稿件是为了传播更多的信息,此类稿件不代表本网观点,本网不承担此类稿件侵权行为的连带责任。故此,如果您发现本网站的内容侵犯了您的版权,请您的相关内容发至此邮箱【779898168@qq.com】,我们在确认后,会立即删除,保证您的版权。