linux cマルチスレッドプログラミングインスタンスコード

2495 ワード

コードを直接見てください.コードに注釈があります.
 
  
#include
#include
#include
#include
#include
#define MAX 3

int number =0;
pthread_t id[2];
pthread_mutex_t mut; //

void thread1(void)
{
    int i;
    printf("Hello,I am pthread1!
");
    for (i=0; i    {
        pthread_mutex_lock(&mut);  // , number
            number ++;  
            printf("Thread1:number = %d
",number);
        pthread_mutex_unlock(&mut);
        sleep(1);  //linux c sleep(minute),
    }
    pthread_exit(NULL); // , 。
}

void thread2(void)
{
    int j;
    printf("Hello,I'm pthread2
");
    for(j=0; j    {
        pthread_mutex_lock(&mut);
             number ++;
             printf("Thread2:number = %d
",number);
        pthread_mutex_unlock(&mut);
        sleep(1);
    }
    pthread_exit(NULL);
}

void thread_create(void)
{
    int temp;
    memset(&id, 0, sizeof(id));
if(temp = pthread_create(&id[0], NULL, (void *)thread1, NULL)!= 0)
                          // :    
                          // 0
        printf("Thread 1 fail to create!
");
    else
        printf("Thread 1 created
");
    if(temp = pthread_create(&id[1], NULL, (void *)thread2, NULL)!= 0)
        printf("Thread 2 fail to create!
");
    else
        printf("Thread 2 created!
");
 }  
void thread_wait()
{
    if(id[0] != 0)
    {
        pthread_join(id[0], NULL); // ,
        printf("Thread1 completed!
");
    }
    if(id[1] != 0)
    {
        pthread_join(id[1], NULL);
        printf("Thread2 completed!
");
    }
}
int main(void)
{
int i,ret1,ret2;
pthread_mutex_init(&mut, NULL); //
    printf("Main fuction,creating thread...
");
    thread_create();
    printf("Main fuction, waiting for the pthread end!
");
    thread_wait();
    return (0);
}