我创建了一个与 pthreadVC.lib
一起使用的小程序,它是 Win32
版本。我使用的是 Visual Studio 2013。
当我更改了同一个程序的x64
程序设置,然后我链接了pthreadVC2.lib(用于x64配置),然后我的程序也在pthread_join
处崩溃了我使用了 pthread_cancel
而不是 join,但遇到了同样的问题。另外,我自己为 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(*)()
。即使您使用了强制转换,但这也是不正确的并且会导致未定义的行为。
关于c - 在 Windows x64 构建上,示例在 pthread_cancel 和 pthread_join 处崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35811835/