天天看點

線程的信号燈

[頭檔案]

#include <semaphore.h>

[建立]

int sem_init(sem_t *sem, int pshared, unsigned int value);

int sem_post(sem_t *sem);(v操作,釋放資源)

int sem_wait(sem_t *sem);(p操作,申請資源)

int sem_trywait(sem_t *sem);(p操作)

int sem_getvalue(sem_t * sem, int * sval);

[銷毀]

int sem_destroy(sem_t * sem);

例子:

#include <stdio.h>

#include <semaphore.h>

sem_t sem;

void *thread(void *arg)

{

 sleep(1);

 while (1)

 {

  sem_wait(&sem);

  printf("this is thread1!\n");

 }

 return (void *)0;

}

int main(int argc, char **argv)

{

 pthread_t id;

 void *ret;

 sem_init(&sem, 0, 0);

 pthread_create(&id, NULL, thread, NULL);

 sleep(1); 

 while (1)

 {

  if (sem_trywait(&sem) < 0)

  {

   printf("sem_post\n");

   sem_post(&sem);

   sleep(2);

  }

 }

 pthread_join(id, &ret);

 return 0;

}

繼續閱讀