pthread_cond_t
#include <stdio.h> #include <stdlib.h> #include <pthread.h> struct msg { struct msg *next; int num; }; struct msg *head = NULL; pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *producer(void *p) { struct msg *mp; for(;;) { mp = malloc(sizeof(struct msg)); mp->num = rand() % 2000 + 1; printf("Producer %d\n",mp->num); pthread_mutex_lock(&lock); mp->next = head; head = mp; pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); sleep(rand() % 5); } return NULL; } void *consumer(void *p) { struct msg *mp; for(;;) { pthread_mutex_lock(&lock); while(head == NULL) pthread_cond_wait(&has_product,&lock); mp = head; head = mp->next; pthread_mutex_unlock(&lock); printf("Consumer %d\n",mp->num); free(mp); sleep(rand() % 5); } return NULL; } int main() { pthread_t pid, cid; srand(time(NULL)); pthread_create(&pid,NULL,producer,NULL); pthread_create(&cid,NULL,consumer,NULL); pthread_join(pid,NULL); pthread_join(cid,NULL); return 0; }
pthread_mutex_t
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define NLOOP 50 int counter = 0; pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER; void* doit(void* p) { int i,val; for( i = 0; i < NLOOP; i++) { pthread_mutex_lock(&counter_mutex); counter++; printf("%x: %d\n",(unsigned int)pthread_self(),counter); pthread_mutex_unlock(&counter_mutex); usleep(1); } return 0; } int main() { pthread_t tidA,tidB; pthread_create(&tidA,NULL,doit,NULL); pthread_create(&tidB,NULL,doit,NULL); pthread_join(tidA,NULL); pthread_join(tidB,NULL); return 0; }
sem_t
#include <stdio.h> #include <stdlib.h> #include <semaphore.h> #include <pthread.h> #define NUM 5 int queue[NUM]; sem_t blank_number, product_number; void *producer(void *p) { int i = 0; while(1) { sem_wait(&blank_number); queue[i] = rand() % 1000 + 1; sem_post(&product_number); printf("product %d\n",queue[i]); i = (i + 1) % NUM; sleep(rand() % 5); } return NULL; } void *consumer(void *p) { int i = 0; while(1) { sem_wait(&product_number); printf("consumer %d\n",queue[i]); queue[i] = 0; sem_post(&blank_number); i = (i+1) % NUM; sleep(rand() % 5); } return NULL; } int main() { pthread_t pid,cid; srand(time(NULL)); sem_init(&blank_number,0,NUM); sem_init(&product_number,0,0); pthread_create(&pid, NULL, producer,NULL); pthread_create(&cid, NULL, consumer,NULL); pthread_join(pid,NULL); pthread_join(cid,NULL); sem_destroy(&blank_number); sem_destroy(&product_number); return 0; }
线程同步