`
zhou347742
  • 浏览: 9744 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
最近访客 更多访客>>
社区版块
存档分类
最新评论

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

阅读更多

坑爹的师父,坑爹的代码……粗略的精简了一下,但是线程的创建还是有点问题,下一版再研究

以下是代码:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define SIZE 5

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 = 0; i < SIZE; i++)
	{
	    rc[i] = pthread_create(&tid[i], NULL, thread, &i);
	    if (rc[i] != 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);
    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);
}

 

  • 大小: 410.3 KB
1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics