使用互斥锁实现共享资源访问
能打印完整的hello world或者HELLO WORLD, 而不是hello和world分离
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_mutex_t m;//定义互斥锁
void err_thread(int ret,char *str)
{
if(ret!=0)
{
fprintf(stderr,"%s:%s\n",str,strerror(ret));
pthread_exit(NULL);
}
}
void *tfn(void *arg)
{
srand(time(NULL));
while(1)
{
//加锁 m--
pthread_mutex_lock(&m);
printf("hello");
printf("world!\n");
//解锁 m++
pthread_mutex_unlock(&m);
sleep(rand()%3);
}
return NULL;
}
int main(void)
{
pthread_t tid;
srand(time(NULL));
int flag=5;
//初始化mutex
pthread_mutex_init(&m,NULL);
//创建线程
int ret = pthread_create(&tid,NULL,tfn,NULL);
err_thread(ret,"pthread_create error");
while(flag--)
{
//加锁 m--
pthread_mutex_lock(&m);
printf("HELLO");
printf("WORLD!\n");
//解锁 m++
pthread_mutex_unlock(&m);
sleep(rand()%3);
}
//取消线程
pthread_cancel(tid);
//等待线程终止
pthread_join(tid,NULL);
//销毁锁
pthread_mutex_destroy(&m);
}