【问题标题】:C thread not behaving correctly - simple codeC 线程行为不正确 - 简单代码
【发布时间】:2011-01-26 09:08:47
【问题描述】:

我正在使用 _beginthreadex 在 c 中创建一个新线程。我已经编写了以下代码。 相同的代码用两个版本编写,第一个版本可以正常工作,但第二个版本不工作。

工作代码

main.c

#include <windows.h>
#include <stdio.h>

extern void func(unsigned (__stdcall *SecondThreadFunc)( void* ));

int main()
{ 
    func(NULL);
}

秒.c

#include<Windows.h>

//when thread start routine is declared in the same file new thread is running fine...
//but if this routine is moved to main.c and passed as parameter to func new thread is not working
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
    printf( "In second thread...\n ");
    return 0;
} 


void func(unsigned (__stdcall *SecondThreadFunc)( void* ))
{
    HANDLE hThread;
    printf( "Creating second thread...\n" );

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

    // Wait until second thread terminates.
    WaitForSingleObject( hThread, INFINITE );
}

代码无效(如下)

main.c

#include <windows.h>
#include <stdio.h>
#include <process.h>


extern void func(unsigned (__stdcall *SecondThreadFunc)( void* ));

unsigned __stdcall SecondThreadFunc( void* pArguments )
{
    printf( "In second thread...\n ");
    return 0;
} 

int main()
{ 
    func(SecondThreadFunc);
}

秒.c

#include<Windows.h>

void func(unsigned (__stdcall *SecondThreadFunc)( void* ))
{
    HANDLE hThread;
    printf( "Creating second thread...\n" );

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

    // Wait until second thread terminates.
    WaitForSingleObject( hThread, INFINITE );
}

在调用 SecondThreadFunc 时,我在 _beginthreadex 中遇到访问冲突。有人能帮帮我吗。提前致谢。

【问题讨论】:

  • printf() 等 stdio 函数不是线程安全的。

标签: c multithreading winapi


【解决方案1】:

在你应该有的无效代码中(注意 &s):

hThread = (HANDLE)_beginthreadex( NULL, 0, SecondThreadFunc, NULL, 0, NULL );

【讨论】:

  • 两者都是函数调用,但为什么上述更正有效......在c函数指针传递给函数时不需要使用&。对吗?
  • @Vineel Kumar Reddy:出于您所说的原因,对func() 调用的更改是不必要的。然而,第二个改变是必要的——func() 中的SecondThreadFunc 是一个函数指针值,所以当你获取它的地址时,你得到的是函数指针的地址,而不是函数的地址。在这种情况下,SecondThreadFunc*SecondThreadFunc 是等价的表达式。
  • 你很棒,虽然我从 6 年就开始用 c 编程,这真的是一个非常微妙的例子。非常感谢
猜你喜欢
  • 2010-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-12
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多