#include <pthread.h>
pthread_t thread[2];
int number=0;//共享资源
pthread_mutex_t mut;
void work1()
{
int i=0;
printf("This is work1\n");
for(i=0;i<10;i++)
{
//共享资源枷锁
pthread_mutex_lock(&mnt);
number++;
pthread_mutex_unlock(&mnt);
printf("number=%d\n",number);
sleep(1);
}
//线程结束
pthread_exit(NULL);
}
void work2()
{
int i=0;
printf("This is work2\n");
for(i=0;i<10;i++)
{
//共享资源枷锁
pthread_mutex_lock(&mnt);
number++;
pthread_mutex_unlock(&mnt);
printf("number=%d\n",number);
sleep(1);
}
//线程结束
pthread_exit(NULL);
}
int main()
{
//线程锁的初始化
pthread_mutex_init(&mnt,NULL);
//创建线程1
pthread_create(&thread[0],NULL,work1,NULL);
//创建线程2
pthread_create(&thread[1],NULL,work2,NULL);
//等待线程1结束
pthread_join(thread[0],NULL);
//等待线程2结束
pthread_join(thread[1],NULL);
}