您的位置:首页 > 其它

使用sem_post信号量进行线程同步

2013-06-28 15:01 260 查看
写了一小段程序,测试一下线程同步的问题,如下:

#include <stdio.h>
#include <string.h>
#include <semaphore.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

sem_t sp;

int val = -1;
int semPost(sem_t * pSem, int nMaxCount)
{
int nRet, nSemCount;

sem_getvalue(pSem, &nSemCount);
if (nSemCount>=nMaxCount)
{
return 0;
}
else
{
nRet=sem_post(pSem);
return nRet;
}
}

int semWait(sem_t * pSem)
{
int nRet;
nRet=sem_wait(pSem);

while (sem_trywait(pSem)==0) {}
return nRet;
}

void xxx()
{
while(1)
{
semWait(&sp);
printf("xxx  val  %d\n",val);
}

}

void yyy()
{
int i = 0;
while(1)
{
//    semPost(&sp,3);
printf("yyy :  %d\n",i);
sleep(1);
if(i++ >= 3)
{
i = 0;
semPost(&sp,3);
val = 9;
printf("now xxx can run !!!\n");
}
}

}

int main(int argc,char **argv)
{
pthread_t x;
pthread_t y;

sem_init(&sp,0,0);

pthread_create(&x,NULL,(void *)xxx,NULL);
pthread_create(&y,NULL,(void *)yyy,NULL);

while(1)
{
sleep(1);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: