在 window x64 构建的示例在 pthread_cancel 和 pthread_join 处崩溃

On window x64 build of example crashing at pthread_cancel and pthread_join

我已经创建了与 pthreadVC.lib 一起工作的小程序,它是 Win32 版本。我正在使用 visual studio 2013.

当我更改了 x64 od 同一个程序的程序设置,然后我链接了 pthreadVC2.lib(对于 x64 配置),然后我的程序也在 pthread_join 崩溃,而不是加入我使用 pthread_cancel 但有同样的问题。我自己也为 x64 构建了 pthread 并链接了那个库,但仍然有同样的问题。

我的测试代码

#include<stdio.h>
#include<pthread.h>

pthread_mutex_t mutex = NULL; 
pthread_cond_t cond = NULL;

void test(){
    pthread_mutex_lock(&mutex);

    printf("\n Threads Working");

    pthread_mutex_unlock(&mutex);
}

void main() {

    pthread_t threadid;

    pthread_create(&threadid,NULL,(void*)test,NULL);

    pthread_join(threadid,NULL);

    printf("\n FINISH ");
    if (getchar())
        return;
} 

在 x64 配置上出现的错误是

Unhandled exception at 0x0000000180002C70 (pthread_dll.dll) in Pthread64_bit.exe: 0xC0000005: Access violation reading location 0x000000000000001A.

编辑: 我还从 pthreads in C – a minimal working example 复制了示例 并尝试 运行 但在 pthread_join 中有同样的错误。

所以你能告诉我是否需要为 x64 或我遗漏的地方做任何其他设置?

互斥锁在使用前必须先初始化。您将它们初始化为 NULL,然后尝试使用它们。这是错误的。

该错误消息清楚地表明一个 NULL 指针在一个小偏移处被取消引用,正在访问一个结构的成员:访问冲突读取位置 0x000000000000001A

因此删除不正确的初始化,并在使用前初始化互斥量:

const int error = pthread_mutex_init( &mutex );
if( error ) 
{
    //handle error
}

并在不再使用时将其删除:

const int error = pthread_mutex_destroy( &mutex );
if( error ) 
{
    //handle error
}

或者,互斥量可以用以下方式初始化:PTHREAD_MUTEX_INITIALIZER:

pthread_mutex mutex = PTHREAD_MUTEX_INITIALIZER ;

它们仍应使用 pthread_mutex_destroy() 删除。

另一个问题是传递给 pthread_create() 的函数。它的类型必须是 void*(*)(void*)。您的函数类型是 void(*)()。即使您使用了强制转换,这也是不正确的并且会导致未定义的行为。