zhou347742 发表于 2013-1-26 12:29:35

创建多线程做减法(简化2)(修改)

对上一次写得再修改,修正了部分问题,但是无法处理过大线程数,可能是系统资源分配问题
代码如下:
#include <pthread.h>#include <stdio.h>#include <stdlib.h>#define SIZE 6int 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 = 1; i < SIZE; i++){    int * argzone = malloc((int)sizeof(int));    *argzone = i;    rc = pthread_create(&tid, NULL, thread, argzone);    if (rc != 0)    printf("The thread%d-create is failed!\n", i);      }//pthread_mutex_lock(&mutex);pthread_cond_wait(&cond, &mutex);//pthread_mutex_unlock(&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/7954/6635895f-868e-30cf-9512-d81a93a5ee4f.png
页: [1]
查看完整版本: 创建多线程做减法(简化2)(修改)