淺析Linux下一個簡單的多線程互斥鎖的例子
更新時間:2013年07月09日 11:21:08 作者:
本篇文章是對Linux下一個簡單的多線程互斥鎖的例子進行了分析介紹,需要的朋友可以參考下
復制代碼 代碼如下:
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t Device_mutex ;
int count=0;
void thread_func1()
{
while(1)
{
pthread_mutex_lock(&Device_mutex);
printf("thread1: %d\n",count);
pthread_mutex_unlock(&Device_mutex);
count++;
sleep(1);
}
}
void thread_func2()
{
while(1)
{
pthread_mutex_lock(&Device_mutex);
printf("thread2: %d\n",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;
}
相關文章
Linux操作系統(tǒng)定時調度系統(tǒng)Cron深入介紹
推薦使用crontab -e命令添加自定義的任務,退出后重啟crond進程,雖然官方文檔描述為“crond命令每分鐘會定期檢查是否有要執(zhí)行的工作,如果有要執(zhí)行的工作便會自動執(zhí)行該工作”2013-08-08