可变数量的线程 C++ [英] Variable number of threads c++

查看:68
本文介绍了可变数量的线程 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个 C++ 程序,该程序创建一个数量 a 的线程,然后对于每个线程 n (0<n<a),要求每个线程对从 0 到n.因此,例如,如果 a=5,我需要创建 5 个线程,第三个线程需要从 0 添加到 3.我使用 main 函数和一个 while 循环来动态创建线程(使用 pthread_create,我必须使用线程).然后我有一个所有线程都运行的通用函数.我的问题是我不知道如何让每个线程知道它是哪个号码.那么,第三个线程如何知道它是第三个而不是第一个.

I need to create a c++ program that creates a number, a, of threads and then for each thread, n (0<n<a), asks each thread to sum numbers from 0 to n. So, for example, if the a=5, I need to create 5 threads and the third thread will need to add from 0 to 3. I use the main function and a while loop to dynamically create threads (using pthread_create, I have to use pthreads). Then I have one generic function that all the threads run. My problem is I don't know how to let each thread know which number is it. So, how would the third thread know that it is the third and not the first.

我确定这很简单,但我一直无法找到答案.

I'm sure this is simple, but I haven't been able to find the answer.

感谢您的帮助!

etk1220

推荐答案

创建可变数量的线程并不难.例如:

Creating a variable amount of threads is not hard. For example:

void * func(void *);

std::vector<pthread_t> threads(n);

for (std::vector<pthread_t>::iterator it = threads.begin(); it != threads.end(); ++it)
{
    int r = pthread_create(&*it, NULL, func, args);
}

您需要添加错误检查和适当的回滚机制,以防出现错误.使用 库会简单得多,但你说你不能使用它.

You'll need to add error checking and a suitable roll-back mechanic in case of errors. With the <thread> library it would be much simpler, but you said you can't use that.

这篇关于可变数量的线程 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆