diff --git a/day7/homework/h3.c b/day7/homework/h3.c new file mode 100644 index 0000000..7b570f5 --- /dev/null +++ b/day7/homework/h3.c @@ -0,0 +1,42 @@ +/* +编写一个程序, 创建多个线程, 每个线程负责对一个共享计数器进行自增操作。要求实现线程间的互斥, 确保每个线程对计数器的自增操作是原子的, 不会出现竞争条件。 +*/ +#include +#include +#include +#include + +sem_t sem; +int number = 0; + +void * +addfun(void *data) +{ + sem_wait(&sem); + number++; + printf("%ld 线程时, number = %d\n", pthread_self(), number); + sem_post(&sem); +} + +int main(int argc, char const *argv[]) +{ + sem_init(&sem, 0, 1); + printf("开始的 number = %d\n", number); + + pthread_t t[5]; + for (int i = 0; i < 5; i++) + { + pthread_create(&t[i], NULL, addfun, NULL); + } + + for (int i = 0; i < 5; i++) + { + pthread_join(t[i], NULL); + } + + printf("现在的 number = %d\n", number); + + sem_destroy(&sem); + + return 0; +}