gpt4 book ai didi

c++ - 如何在 C++、Windows 7 中使用 _beginthread 方法在线程中发送和接收参数

转载 作者:行者123 更新时间:2023-11-28 03:44:56 25 4
gpt4 key购买 nike

我要执行上述操作。

void myFunc(void *parameters)
{
myObject myObj = // Here I would like to receive the object I passed from the main

... // several stuff
}

...

int main()
{
...
myObject myObj(...);
_beginthread(myFunc, // Here I would like to pass on the object I created above)
...
}

提前感谢您的宝贵时间。祝你有愉快的一天!

最佳答案

直接来自 Microsoft's documentation _beginthreadex:

// crt_begthrdex.cpp
// compile with: /MT
#include <windows.h>
#include <stdio.h>
#include <process.h>

int Counter;
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
printf( "In second thread...\n" );

while ( Counter < 1000000 )
Counter++;

_endthreadex( 0 );
return 0;
}

int main()
{
HANDLE hThread;
unsigned threadID;

printf( "Creating second thread...\n" );

// Create the second thread.
hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );

// Wait until second thread terminates. If you comment out the line
// below, Counter will not be correct because the thread has not
// terminated, and Counter most likely has not been incremented to
// 1000000 yet.
WaitForSingleObject( hThread, INFINITE );
printf( "Counter should be 1000000; it is-> %d\n", Counter );
// Destroy the thread object.
CloseHandle( hThread );
}

更新:如何在没有全局变量的情况下使用参数。

#include <iostream>
#include <process.h>

using namespace std;

void myFunction( void* arg){

MyObject myObj = *(MyObject*)arg;

// do something with your object

_endthread();

}

int main(int argc, char *argv[])
{
MyObject myObj(/*...*/);

_beginthread( myFunction, 0, (void*)&myObj);

// You can also use the example above for hints on how
// to wait for the thread to terminate before exiting
// your application.
return 0;
}

提示:用你的对象替换 int

关于c++ - 如何在 C++、Windows 7 中使用 _beginthread 方法在线程中发送和接收参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7947796/

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