#include <pthread.h> #include <stdio.h> #include <sys/time.h> #include <string.h> #define MAX 10 #define MAXTHREAD 100 pthread_t thread[MAXTHREAD]; pthread_mutex_t mut; int number=0; typedef struct { int a; }countStruct; void *thread1(void *threadcount) { countStruct *tc; int i; int count; tc = (countStruct *)threadcount; // printf ("thread1 : I'm thread 1\n"); for (i = 0; i < MAX; i++) { // printf("thread[%d] : number = %d, i = %d\n", *tc, number, i); pthread_mutex_lock(&mut); // usleep(500000); count = number; usleep(100); count++; number = count; pthread_mutex_unlock(&mut); printf("thread[%d] : number++ = %d, i = %d\n", tc->a, number, pthread_self()); // sleep(2); } // printf("thread1 :主函數(shù)在等我完成任務嗎?\n"); pthread_exit(NULL); } //void thread_create(void) //{ // int temp, k; // memset(&thread, 0, sizeof(thread)); //comment1 // /*創(chuàng)建線程*/ // for(k = 0; k < MAXTHREAD; k++) // { //// sleep(1); // if((temp = pthread_create(&thread[k], NULL, thread1, (void *)&k)) != 0) //comment2 // // printf("thread create error!\n"); // else // printf("thread[%d] is created\n", k); // } //} void thread_wait(void) { int i; for(i = 0; i < MAXTHREAD; i++) { if(thread[i] != 0) { pthread_join(thread[i],NULL); printf("thread[%d] is finished\n", i); } } } int main() { int temp,k; countStruct cs[MAXTHREAD]; /*用默認屬性初始化互斥鎖*/ pthread_mutex_init(&mut,NULL); printf("i'm main function, i'm creating threads\n"); /////////////////// memset(&thread, 0, sizeof(thread)); //comment1 /*創(chuàng)建線程*/ for(k = 0; k < MAXTHREAD; k++) { cs[k].a = k; if((temp = pthread_create(&thread[k], NULL, thread1, (void *)&cs[k])) != 0) //comment2 printf("thread create error!\n"); else printf("thread[%d] is created\n", k); } /////////////////// printf("i'm main function, i'm waiting for my threads\n"); thread_wait(); return 0; } |
|
來自: astrotycoon > 《thread》