Multithreading counts, with each thread accumulating 10 numbers.
Realize:
1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <errno.h>5#include <pthread.h>6 7 pthread_mutex_t Num_lock;8 9 intnum =0;Ten intsum =0; One A void*foo1 () - { - #if1 thePthread_mutex_lock (&num_lock); - for(inti =0;i<Ten;++i) - { -num + =1; +Sum + =num; -printf"thread 1,num =%d,sum =%d\n", num,sum); +UsleepTen); A } atPthread_mutex_unlock (&num_lock); - #else - for(inti =0;i<Ten;++i) - { -num + =1; -Sum + =num; inprintf"thread 1,num =%d,sum =%d\n", num,sum); -UsleepTen); to } + #endif - returnNULL; the } * $ void*Foo2 ()Panax Notoginseng { - #if1 thePthread_mutex_lock (&num_lock); + for(inti =0;i<Ten;++i) A { thenum + =1; +Sum + =num; -printf"thread 2,num =%d,sum =%d\n", num,sum); $UsleepTen); $ } -Pthread_mutex_unlock (&num_lock); - #else the for(inti =0;i<Ten;++i) - {Wuyinum + =1; theSum + =num; -printf"thread 2,num =%d,sum =%d\n", num,sum); WuUsleepTen); - } About #endif $ returnNULL; - } - - intMainintargcChar*argv[]) A { + pthread_t Tid1,tid2; the interr; - $Pthread_mutex_init (&num_lock,null); the theErr = Pthread_create (&tid1,null,foo1,null); the if(Err! =0) the { -printf"Error code:%d,reason:%s\n", Err,strerror (err)); in return-1; the } the AboutErr = Pthread_create (&tid2,null,foo2,null); the if(Err! =0) the { theprintf"Error code:%d,reason:%s\n", Err,strerror (err)); + return-1; - } the Bayi //for (int i = 0;i<10;++i) the //printf ("main thread, num =%d\n", num++); the -Err =Pthread_join (tid1,null); - if(Err! =0) the { theprintf"Error code:%d,reason:%s\n", Err,strerror (err)); the return-1; the } -Err =Pthread_join (tid2,null); the if(Err! =0) the { theprintf"Error code:%d,reason:%s\n", Err,strerror (err));94 return-1; the } the thePthread_mutex_destroy (&num_lock);98 About return 0; -}
Code Sea supplements: Linux multi-threaded mutex lock