gpt4 book ai didi

c++ - C++中的多线程

转载 作者:太空狗 更新时间:2023-10-29 19:36:48 24 4
gpt4 key购买 nike

我想在不同线程上运行一个具有不同参数的函数:

int threads = 3;
int par1[] = {1, 2, 3};
int par2[] = {4, 5, 6};
for (int i=0; i<threads; i++){
//new_thread function(par1[i], par2[i]);
}

我对线程一无所知。我试图做一些 Windows API(不能使用其他库),但它不起作用。我应该如何实现?并且有可能在编程时启动未知数量的线程(动态创建线程)?

最佳答案

Windows 的一个示例,

#include <Windows.h>

struct thread_data
{
int m_id;
thread_data(int id) : m_id(id) {}
};
DWORD WINAPI thread_func(LPVOID lpParameter)
{
thread_data *td = (thread_data*)lpParameter;
cout << "thread with id = " << td->m_id << endl;
return 0;
}
int main()
{
for (int i=0; i< 10; i++)
{
CreateThread(NULL, 0, thread_func, new thread_data(i) , 0, 0);
}
}

在这个例子中,每个线程获取不同的数据,即thread_data类型的数据,这些数据作为参数传递给线程函数thread_func()

阅读这些以了解如何在 Windows 上创建线程:

http://msdn.microsoft.com/en-us/library/ms682516(VS.85).aspx
http://msdn.microsoft.com/en-us/library/ms682453(v=vs.85).aspx


此外,您可能也喜欢这个建议:

Better design : define a reusable class!

关于c++ - C++中的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4768294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com