坑爹的师父,坑爹的代码……粗略的精简了一下,但是线程的创建还是有点问题,下一版再研究
以下是代码:
#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
分享到:
相关推荐
基于vs2013平台,创建多线程的教程,基于vs2013平台,创建多线程的教程,基于vs2013平台,创建多线程的教程
如标题,在MFC中必须使用 AfxBeginThread创建多线程,如使用BeginThread可能会出现BUG
采用_beginthread创建多线程,创建尽可能多的线程,直到系统不能创建为止,创建数目实时动态显示。
C# winform 动态创建和 关闭多线程,基于VS2010的完整解决方案。 可运行
火车票售票系统 创建多线程火车票售票系统 创建多线程火车票售票系统 创建多线程火车票售票系统 创建多线程火车票售票系统 创建多线程
《MFC多线程的创建,包括工作线程和用户界面线程》全面讲解MFC多线程的创建,界面多线程与工作者多线程,多线程的起源、继承与派生,两多线程之间的区别与相同点,定时器与多线程的关系与异同(定时器是定时优先抢占...
VC++创建多线程 线程池 线程调度 线程同步
多线程实例化bean,创建多线程时可注入
在Java中只支持单继承,因此通过继承Thread类创建线程有一定的局限性,这时可以使用另一种方式,即实现Runnable接口来...接下来在案例中将通过实现Runnable接口方式创建线程,并实现多线程分别打印0~99的数字的功能。
在Arduino中使用ProtoThread创建多线程系统
操作系统程序-创建多线程,还有读者写者问题,希望对你有帮助,欢迎大家下载
创建线程创建线程创建线程创建线程创建线程创建线程创建线程创建线程
多线程的应用 主要是描述事件对象的创建和线程的同步
VB可不可以创建多线程呢? 进程:是指程序在一个数据集合上运行的过程,是操作系统进行资源分配和调度运行的一个独立单位,简单来说进程就是程序的一次执行。
这是一个Delphi使用API来创建多线程应用程序的示例。IsDone变量的引入,是为了避免控制台应用的主线程执行结束时,进程中止导致新创建线程中止。——这甚至可能发生在新线程执行writeln()之前。 在线程函数中,...
C#创建多线程应用程序
c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程c_多线程...
操作系统的第二个实验,Linux多线程创建
多线程实例,可创建任意多线程!本例子类似模拟卖火车票的流程,通过TRACE打印程序调试信息!
Java多线程--对比创建多线程的两种方式