From 663a501a63ea95fc0ec6ed0e148c00bb6440d820 Mon Sep 17 00:00:00 2001 From: flykhan Date: Tue, 22 Aug 2023 23:34:57 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A4=9A=E4=BB=BB=E5=8A=A1=E4=BA=92=E6=96=A5?= =?UTF-8?q?=E4=B8=8E=E5=90=8C=E6=AD=A5(=E4=BA=92=E6=96=A5=E9=94=81,=20?= =?UTF-8?q?=E8=AF=BB=E5=86=99=E9=94=81,=20=E6=9D=A1=E4=BB=B6=E5=8F=98?= =?UTF-8?q?=E9=87=8F,=20=E4=BF=A1=E5=8F=B7=E9=87=8F,=20=E5=91=BD=E5=90=8D?= =?UTF-8?q?=E4=BF=A1=E5=8F=B7=E9=87=8F):=20=E4=BD=9C=E4=B8=9A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day7/homework/h3.c | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 day7/homework/h3.c 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; +}