Linux thread problems-general Linux technology-Linux technology and application information, the following is a detailed description.
CODE: # include
# Include
# Include
# Include
# Include
# Include
# Define MAX_THREAD 3 // Number of threads
Unsigned long main_counter, counter [MAX_THREAD];
Void * thread_worker (void *);
Int main (int argc, char * argv [])
{
Int I, rtn, ch;
Pthread_t pthread_id [MAX_THREAD] = {0}; // store each thread to the id
For (I = 0; I <MAX_THREAD; I ++ ){
If (pthread_create (& pthread_id [I], NULL, thread_worker, & I ))
Printf ("thread_create failed... \ n ");
Sleep (1 );
}
Do {
Unsigned long sum = 0;
For (I = 0; I <MAX_THREAD; I ++ ){
Sum + = counter [I];
Printf ("counter [% d]: % llu \ n", I + 1, counter [I]);
}
Printf ("main_counter: % llu/sum: % llu \ n", main_counter, sum );
} While (ch = getchar ()! = 'Q '));
Return 0;
}
Void * thread_worker (void * p)
{
Int thread_num;
Thread_num = * (int *) p;
For (;;){
Counter [thread_num] ++;
Main_counter ++;
}
} |