对上一次写得再修改,修正了部分问题,但是无法处理过大线程数,可能是系统资源分配问题
代码如下:
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #define SIZE 6 int 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[SIZE]; int i, rc[SIZE] = {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[i] = pthread_create(&tid[i], NULL, thread, argzone); if (rc[i] != 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); else printf("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); }