zhou347742 发表于 2013-1-31 00:47:20

创建多线程做减法(简化1)

坑爹的师父,坑爹的代码……粗略的精简了一下,但是线程的创建还是有点问题,下一版再研究
以下是代码:
#include <pthread.h>#include <stdio.h>#include <stdlib.h>#define SIZE 5int sum;static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;void * thread(void *);int main(int argc, char *argv[]){    pthread_t tid;    int i, rc = {0, 0, 0, 0, 0};    printf("enter main\n");    printf("Please input a number : \n");    scanf("%d", &sum);    while (sum >= 0)    {for (i = 0; i < SIZE; i++){    rc = pthread_create(&tid, NULL, thread, &i);    if (rc != 0)    printf("The thread%d-create is failed!\n", i);      }    }    pthread_cond_wait(&cond, &mutex);    printf("leave main\n");    exit(0);}void * thread(void *arg){    int * nArg = (int *)arg;    printf("enter thread%d\n", *nArg);    pthread_mutex_lock(&mutex);    if (sum <= 0)exit(0);    elseprintf("This is thread%d, sum : %d, thread id is %u\n", *nArg, sum, (unsigned int)pthread_self());    pthread_cond_signal(&cond);    sum -= (*nArg);    printf("This is thread%d, sum : %d, thread id is %u\n", *nArg, sum, (unsigned int)pthread_self());    pthread_mutex_unlock(&mutex);    printf("leave thread%d\n", *nArg);    pthread_exit(0);} 
http://dl.iteye.com/upload/attachment/0068/7802/3fc5a77d-298b-3309-83da-8dce0ec99535.png
页: [1]
查看完整版本: 创建多线程做减法(简化1)