mutex.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
#include<semaphore.h>
int i=0;
pthread_mutex_t mutex;
void *f(void *buf)
{
char b[]="change";
printf("buf in the created pthread:%s\n",(char *)buf);
strncpy(buf, b, 6);
pthread_mutex_lock(&mutex);//加锁
i = 2;
printf("in pthread i=: %d\n",i);
sleep(1);
i = i+1;
printf("in pthread second i=: %d\n",i);
pthread_mutex_unlock(&mutex);//解锁
pthread_exit("ok,the join to exit is success!");
}
int main()
{
pthread_t tid;
void *result;
char buf[]="test for the pthread\n";
if((pthread_mutex_init(&mutex, NULL)) == -1)
{
printf("init failure");
}
pthread_create(&tid, NULL, f, (void *)buf);//需要放在创建锁的后面,否则有问题
pthread_mutex_lock(&mutex);//加锁
i = 1;
printf("in main i=: %d\n",i);
sleep(1);
i = i+1;
printf("in main second i=: %d\n",i);
pthread_mutex_unlock(&mutex);//解锁
printf("buf in main:%s\n",buf);
pthread_join(tid, &result);
printf("the return is : %s\n",(char *)result);
return 0;
}