thread 多线程

thread 多线程

多线程

编写多线程程序时,在设计上要特别小心.
对共享变量,多个执行路径,要引起足够重视.

创建多线程:
/*
 * 多线程
 
*/
#include 
< stdio.h >
#include 
< unistd.h >
#include 
< stdlib.h >
#include 
< pthread.h >

#define  NUM_THREADS 6

void   * thread_function( void   * arg);

int  main(){
    
int  res;
    pthread_t a_thread[NUM_THREADS];
    
void   * thread_result;
    
int  lots_of_threads;

    
for (lots_of_threads  =   0 ; lots_of_threads  <  NUM_THREADS; lots_of_threads ++ ){
        printf(
" before pthread_create, lots_of_threads=%d\n " ,lots_of_threads);
        res 
=  pthread_create( & (a_thread[lots_of_threads]),NULL,
                thread_function, (
void   * ) & lots_of_threads);
        
if (res  !=   0 ){
            perror(
" Thread creation failed " );
            exit(EXIT_FAILURE);
        }
    }

    printf(
" Waiting for threads to finish\n " );

    
for (lots_of_threads  =  NUM_THREADS  -   1 ; lots_of_threads  >=   0 ; lots_of_threads -- ){
        res 
=  pthread_join(a_thread[lots_of_threads],  & thread_result);
        
if (res  ==   0 ){
            perror(
" Picked up a thread\n " );
        }
        
else {
            perror(
" pthread_join failed\n " );
        }
    }

    printf(
" All done\n " );
    exit(EXIT_SUCCESS);
}

void   * thread_function( void   * arg){
    
int  my_number  =   * ( int   * )arg;
    
int  rand_num;

    printf(
" thread_funcion is running. Argument was %d\n " , my_number);
    rand_num 
=   1 + ( int )( 9.0 * rand() / (RAND_MAX + 1.0 ));
    sleep(rand_num);
    printf(
" Bye from %d\n " , my_number);
    pthread_exit(NULL);
}

执行结果:
[green@colorfulgreen ch11]$ gcc  - D_REENTRANT thread8.c  - o thread8  - lpthread
[green@colorfulgreen ch11]$ .
/ thread8    
before pthread_create, lots_of_threads
= 0
before pthread_create, lots_of_threads
= 1
before pthread_create, lots_of_threads
= 2
before pthread_create, lots_of_threads
= 3
before pthread_create, lots_of_threads
= 4
before pthread_create, lots_of_threads
= 5
Waiting 
for  threads to finish
thread_funcion 
is  running. Argument was  5
thread_funcion 
is  running. Argument was  5
thread_funcion 
is  running. Argument was  5
thread_funcion 
is  running. Argument was  5
thread_funcion 
is  running. Argument was  5
thread_funcion 
is  running. Argument was  5
Bye from 
5
Bye from 
5
Picked up a thread
: Success
Bye from 
5
Picked up a thread
: Success
Bye from 
5
Picked up a thread
: Success
Bye from 
5
Picked up a thread
: Success
Bye from 
5
Picked up a thread
: Success
Picked up a thread
: Success
All done

从执行结果里,很显然看到有bug,5个线程的argument全是5.
因为新线程的参数,是使用地址引用传递的:
res  =  pthread_create( & (a_thread[lots_of_threads]),NULL,
                  thread_function,  ( void   * ) & lots_of_threads );
主线程创建线程循环,很快执行完. 引用地址中的值,在子线程执行前,已经被改成了5.
线程参数改成值传递就好了.

--
FROM:Linux程序设计

你可能感兴趣的:(thread 多线程)