您的位置:首页 > 运维架构 > Linux

Linux c multiple threads programming

2011-08-29 21:12 211 查看
/***
thread.c

compile command:

    #gcc -lpthread thread.c -o thread

***/

#include <pthread.h>

#include <stdio.h>

#include <sys/time.h>

#include <string.h>

#define MAX 10

pthread_t thread[2]; //pthread identifier array

pthread_mutex_t mut; //exclusive lock

int number=0, i; //an global integer

void *thread1() //function for thread 1

{

printf ("thread1 : I'm thread 1\n");

for (i = 0; i < MAX; i++)

{

printf("thread1 : number = %d\n",number);

pthread_mutex_lock(&mut); //lock the mutex

number++; //increase the global integer

pthread_mutex_unlock(&mut); //unlock the mutex

sleep(2);

}

printf("thread1 : is the main process waiting for me?\n");

pthread_exit(NULL); //thread exit

}

void *thread2() //function for thread 2

{

printf("thread2 : I'm thread 2\n");

for (i = 0; i < MAX; i++)

{

printf("thread2 : number = %d\n",number);

pthread_mutex_lock(&mut); //lock the mutex

number++; //increase the global integer

pthread_mutex_unlock(&mut); //unlock the mutex

sleep(3);

}

printf("thread2 : is the main process waiting for me?\n");

pthread_exit(NULL); //thread exit

}

void thread_create(void)

{

int temp;

memset(&thread, 0, sizeof(thread));

if((temp = pthread_create(&thread[0], NULL, thread1,
NULL)) != 0) //create thread 1

printf("Create thread1 failed.\n");

else

printf("Create thread1 success.\n");

if((temp = pthread_create(&thread[1], NULL, thread2,
NULL)) != 0) //create thread 2

printf("Create thread2 failed.\n");

else

printf("Create thread2 success.\n");

}

void thread_wait(void)

{

if(thread[0] !=0) {

pthread_join(thread[0],NULL); //wait for thread 1 to exit

printf("thread1 exit.\n");

}

if(thread[1] !=0) {

pthread_join(thread[1],NULL); //wait for thread 2 to exit

printf("thread1 exit.\n");

}

}

int main()

{

pthread_mutex_init(&mut,NULL); //initialize mutex lock

printf("main: creating threads...\n");

thread_create(); //create threads

printf("main: waiting for threads to complete and exit...\n");

thread_wait(); //wait for threads to exit

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: