六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 19|回复: 0

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

[复制链接]

升级  92%

12

主题

12

主题

12

主题

童生

Rank: 1

积分
46
 楼主| 发表于 2013-1-31 10:35:58 | 显示全部楼层 |阅读模式
坑爹的师父,坑爹的代码……粗略的精简了一下,但是线程的创建还是有点问题,下一版再研究
以下是代码:
#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[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 = 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);} 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表