线程信号量

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
#include<semaphore.h>

sem_t sem;
void *f(void *buf)
{
 sem_wait(&sem);//P操作,只有等V操作过后才能往下运行
 printf("can operate\n");
 char b[]="change";
 printf("buf in the created pthread:%s\n",(char *)buf);
 strncpy(buf, b, 6);
 pthread_exit("ok,the join to exit is success!");
}

int main()

 pthread_t tid;
 void *result;
 char buf[]="test for the pthread\n";
 pthread_create(&tid, NULL, f, (void *)buf);//创建线程
 sem_init(&sem, 0, 0);//初始化信号量,初始值为0;
 sleep(3);
 printf("buf in main:%s\n",buf);
 sem_post(&sem);//打印后执行V操作
 pthread_join(tid, &result);
 printf("the return is : %s\n",(char *)result);
 return 0;
}

posted on 2012-04-08 17:55  小风儿_xf  阅读(162)  评论(0编辑  收藏  举报

导航