将函数作为参数传递以简化线程创建

Passing functions as parameters in order to simplify thread creation

本文关键字:线程 创建 参数传递 函数      更新时间:2023-10-16

我试图写一小段代码,只是使使用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;
    }
}

我想一切都会如我所愿。