互斥锁

xiaoxiao2021-02-28  135

#include <stdio.h> #include <time.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #include <string.h> int tickets = 100; pthread_mutex_t mutex; void delay() { int k1 = rand()000+1; while (k1) { int k2 = rand()000+1;; while(k2) { k2--; } k1--; } } void * sale_a(void *arg) { int current_tickets; while(1) { pthread_mutex_lock(&mutex); current_tickets = tickets; if (current_tickets <= 0) { pthread_mutex_unlock(&mutex); break; } printf ("sale_a has sold a ticket: %d\n", current_tickets); delay(); current_tickets--; tickets = current_tickets; pthread_mutex_unlock(&mutex); } } void *sale_b(void * arg) { int current_tickets; while(1) { pthread_mutex_lock(&mutex); current_tickets = tickets; if (current_tickets <= 0) { pthread_mutex_unlock(&mutex); break; } printf ("sale_b has sold a ticket: %d\n", current_tickets); delay(); current_tickets--; tickets = current_tickets; pthread_mutex_unlock(&mutex); } } int main() { pthread_t tid1, tid2; int ret; srand((unsigned int)time(NULL)); pthread_mutex_init(&mutex, NULL); ret = pthread_create(&tid1, NULL, sale_a, NULL); if (ret != 0) { printf ("create sale_a thread fail: %s", strerror(ret)); return -1; } ret = pthread_create(&tid2, NULL, sale_b, NULL); if (ret != 0) { printf ("create sale_a thread fail: %s", strerror(ret)); return -1; } ret = pthread_join(tid1, NULL); if (ret != 0) { printf("wait thread terminates fail:%s", strerror(ret)); return -1; } ret = pthread_join(tid2, NULL); if (ret != 0) { printf("wait thread terminates fail:%s", strerror(ret)); return -1; } pthread_mutex_destroy(&mutex); return 0; }
转载请注明原文地址: https://www.6miu.com/read-29617.html

最新回复(0)