- 线程互斥pthread_mutex_t
线程间除堆栈不同之外,代码区和数据段都在一个空间中。如果不进行控制会造成数据混乱,简单的使用pthread_mutex_t实现线程互斥的测试
//thread_lock.c
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
static int value =0;
pthread_mutex_t mutex; //控制线程互斥,否则会造成pthread1和2同时对value变量进行操作造成混乱
void *func()
{
while( value < 10 )
{
//sleep(5);
//printf("pthread:%ld,")
pthread_mutex_lock(&mutex);
printf("mutex:%ld\n",mutex);
printf("phread:%ld begin\n",pthread_self());
value++;
sleep(5);
printf("phread:%ld,value=%d\n",pthread_self(),value);
printf("pthread:%ld end\n",pthread_self());
pthread_mutex_unlock(&mutex);
sleep(1); //当前的线程释放代码段,阻塞的线程获取到代码段并执行
}
}
int main()
{
pthread_t pthread1,pthread2;
if(pthread_create(&pthread1,NULL,func,NULL))
{
return -1;
}
sleep(1);
if(pthread_create(&pthread2,NULL,func,NULL))
{
return -1;
}
pthread_join( pthread1 , NULL);
pthread_join( pthread2 , NULL);
// while(1)
// sleep(0);
return 0;
}
gcc thread_lock.c -o thread_lock -lpthread