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

时间:2023-03-09 15:31:33
使用sem_post信号量进行线程同步

写了一小段程序,测试一下线程同步的问题,如下:

#include <stdio.h>
#include <string.h>
#include <semaphore.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h> sem_t sp; int val = -;
int semPost(sem_t * pSem, int nMaxCount)
{
int nRet, nSemCount; sem_getvalue(pSem, &nSemCount);
if (nSemCount>=nMaxCount)
{
return ;
}
else
{
nRet=sem_post(pSem);
return nRet;
}
} int semWait(sem_t * pSem)
{
int nRet;
nRet=sem_wait(pSem); while (sem_trywait(pSem)==) {}
return nRet;
} void xxx()
{
while()
{
semWait(&sp);
printf("xxx val %d\n",val);
} } void yyy()
{
int i = ;
while()
{
// semPost(&sp,3);
printf("yyy : %d\n",i);
sleep();
if(i++ >= )
{
i = ;
semPost(&sp,);
val = ;
printf("now xxx can run !!!\n");
}
} } int main(int argc,char **argv)
{
pthread_t x;
pthread_t y; sem_init(&sp,,); pthread_create(&x,NULL,(void *)xxx,NULL);
pthread_create(&y,NULL,(void *)yyy,NULL); while()
{
sleep();
} return ;
}