C/Semaphore

From Attie's Wiki
(Difference between revisions)
Jump to: navigation, search
(Created page with "Very brief show-how for semaphores on linux. Please note, that there isn't sufficient thread handling code here, just the minimum to make a thread run. <source lang="c"> #inc...")

Revision as of 12:41, 19 November 2012

Very brief show-how for semaphores on linux. Please note, that there isn't sufficient thread handling code here, just the minimum to make a thread run.

#include <stdio.h>
#include <stdlib.h>
 
#include <pthread.h>
#include <semaphore.h>
 
void *myThread(void *p) {
  sem_t *sem = p;
 
  printf("Thread started!\n");
 
  sleep(5);
 
  printf("Poking semaphore\n");
  sem_post(sem);
 
  return NULL;
}
 
int main(int argc, char *argv[]) {
  sem_t sem;
  pthread_t tid;
 
  sem_init(&sem, 0, 0);
 
  printf("Creating thread...\n");
  pthread_create(&tid, NULL, myThread, (void*)&sem);
 
  printf("Waiting on thread...\n");
  sem_wait(&sem);
 
  printf("Tidying up!\n");
  sem_destroy(&sem);
 
  return 0;
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox