将函数作为参数传递以简化线程创建
Passing functions as parameters in order to simplify thread creation
我试图写一小段代码,只是使使用CreateThread()稍微更干净的外观。我不能说我真的打算使用它,但我认为对于像我这样的新程序员来说,这将是一个有趣的小项目。以下是目前为止的内容:
#include <iostream>
#include <windows.h>
using namespace std;
void _noarg_thread_create( void(*f)() )
{
cout << "Thread created...n" << endl;
Sleep(10);
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)f, NULL, 0, NULL);
}
template <typename T>
void _arg_thread_create( void(*f)(T), T* parameter)
{
cout << "Thread created...n" << endl;
Sleep(10);
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)*f, parameter, 0, NULL);
}
void printnums(int x)
{
for(int i = x; i < 100; i++)
{
cout << i << endl;
}
}
void printnumsnoarg()
{
for(int i = 0; i < 100; i++)
{
cout << i << endl;
}
}
int main()
{
cin.get();
_noarg_thread_create( &printnumsnoarg );
cin.get();
int x = 14;
_arg_thread_create( &printnums, &x );
cin.get();
}
基本上我有两个函数将调用CreateThread的两个不同的预设:一个用于线程中需要参数时,一个用于线程中不需要参数时。我可以用g++编译器(cygwin)编译它,它运行时没有任何错误。第一个线程被正确地创建,它像预期的那样打印出数字0-99。然而,第二个线程不打印任何数字(使用此代码,它应该打印14-99)。我的输出如下所示:
<start of output>
$ ./a.exe
Thread created...
0
1
2
3
.
.
.
97
98
99
Thread Created...
<end of output>
你知道为什么第二个线程不能正常工作吗?
你实际上似乎错过了你传递一个指针到你的printnums(int x)
函数。由于x
在main函数中的存储位置将比100大得多,因此循环永远不会运行。
您应该尝试将printnums
更改为:
void printnums(int *x)
{
for(int i = *x; i < 100; i++)
{
cout << i << endl;
}
}
我想一切都会如我所愿。
相关文章:
- 两个线程一个使用流 Api,另一个线程创建文件失败并出现错误ERROR_SHARING_VIOLATION
- C++ 线程创建/删除与线程停止/恢复
- Qt - 如何从线程创建 QFuture
- 我可以使用Qt线程ID为每个线程创建唯一的缓存吗?
- 零MQ 后台线程创建
- OpenMP 线程创建
- GLFW & ImGui:从 main 以外的线程创建 ImGui 控件
- 对象:无法为位于不同线程中的父线程创建子级
- C++ 11:线程创建给我一个"Attempt to use a deleted function"错误
- C 的周期性线程创建
- MPI - 当数组初始化值必须为常量时,如何为工作线程创建部分数组
- 当主GUI线程被阻塞时,如何从工作线程创建无模式对话框
- 多个线程创建5个线程来计算质数
- 为线程创建模板
- 线程创建,CRT和DLL是如何完成的?
- 同步线程创建和销毁(静态)对象
- 竞争条件:一个线程创建静态对象,另一个线程在初始化完成之前使用它.如何处理
- 从不同线程创建QMainWindow
- QFuture 无法为位于不同线程中的父线程创建子级
- ( QNativeSocketEngine)QObject:无法为位于不同线程中的父线程创建子级