mirror of
https://github.com/riba2534/TCP-IP-NetworkNote.git
synced 2026-04-13 18:00:00 +08:00
P296 18.3 线程存在的问题和临界区
This commit is contained in:
30
ch18/thread3.c
Normal file
30
ch18/thread3.c
Normal file
@@ -0,0 +1,30 @@
|
||||
#include <stdio.h>
|
||||
#include <pthread.h>
|
||||
void *thread_summation(void *arg);
|
||||
int sum = 0;
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
pthread_t id_t1, id_t2;
|
||||
int range1[] = {1, 5};
|
||||
int range2[] = {6, 10};
|
||||
|
||||
pthread_create(&id_t1, NULL, thread_summation, (void *)range1);
|
||||
pthread_create(&id_t2, NULL, thread_summation, (void *)range2);
|
||||
|
||||
pthread_join(id_t1, NULL);
|
||||
pthread_join(id_t2, NULL);
|
||||
printf("result: %d \n", sum);
|
||||
return 0;
|
||||
}
|
||||
void *thread_summation(void *arg)
|
||||
{
|
||||
int start = ((int *)arg)[0];
|
||||
int end = ((int *)arg)[1];
|
||||
while (start <= end)
|
||||
{
|
||||
sum += start;
|
||||
start++;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
Reference in New Issue
Block a user