我的命令行工具一直在抛出bus error: 10消息。Xcode调试器显示EXC_BAD_ACCESS消息,并突出显示创建线程的函数调用。手动调试显示,执行流在线程流中的任意位置中断。我试过另一个编译器(gcc),但结果还是一样。禁用pthread_mutex_lock()和pthread_mutex_unlock()没有帮助。我编写了一个复制错误的小示例。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
typedef struct thread_args {
pthread_mutex_t* mutex;
} thread_args;
void* test(void* t_args) {
printf("Thread initiated\n");
thread_args* args = (thread_args* )t_args;
printf("Args casted\n");
pthread_mutex_lock(args->mutex);
printf("Mutex locked\n");
pthread_mutex_unlock(args->mutex);
printf("Mutex unlocked\n");
pthread_exit(NULL);
}
int main() {
pthread_mutex_t mutex1;
pthread_mutex_init(&mutex1, NULL);
thread_args args;
args.mutex = &mutex1;
pthread_t* thread;
printf("Initiating a thread\n");
pthread_create(thread, NULL, test, &args);
return(0);
}发布于 2015-06-23 19:42:09
我想,就你而言,
pthread_create(thread, NULL, test, &args);在这个调用中,thread是一个指针,而不是分配的内存。因此,从本质上说,pthread_create()试图写入未初始化的内存,从而创建未定义行为。
参考pthread_create()的手册页
在返回之前,对
pthread_create()的成功调用将新线程的ID存储在thread指向的缓冲区中;.
相反,你可以
pthread_t thread;
...
pthread_create(&thread, NULL, test, &args);发布于 2015-06-23 19:49:22
您正在使用指向pthread_t的未初始化指针。pthread_t的实际存储需要在某个地方!
试着:
int main() {
pthread_mutex_t mutex1;
pthread_mutex_init(&mutex1, NULL);
thread_args args;
args.mutex = &mutex1;
pthread_t thread;
printf("Initiating a thread\n");
pthread_create(&thread, NULL, test, &args);
return(0);
}发布于 2015-06-23 20:33:17
正如其他答案所指出的,您需要初始化指针thread,只需使用以下方法:
pthread_t thread;
pthread_create(&thread, NULL, test, &args);那么我必须动态地分配内存,因为不同的线程是在许多不同的函数中产生的,因此我不能使用局部变量,因为我不会加入这些线程。那么,我如何在不等待线程完成的情况下释放分配的内存,即不调用join?
不是的。您不需要仅仅因为要生成多个线程就需要动态分配。一旦创建了线程,就不再需要线程标识符了,所以无论它是局部变量还是malloced都不重要。只有当您需要join或更改线程的某些特性时才需要它--为此您需要ID。否则,您甚至可以重用同一个线程来创建多个线程。例如,
pthread_t thread;
for( i = 0; i<8; i++)
pthread_create(&thread, NULL, thread_func, NULL);完全没问题。如果需要,线程总是可以通过调用pthread_self()来获得自己的ID。但是您不能将局部变量mutex1传递给线程函数,因为一旦main线程退出,mutex1就不再存在,因为创建的线程将继续使用它。因此,您要么需要malloc mutex1,要么将其设置为全局变量。
另一件事是,如果您决定让主线程退出,那么您应该调用pthread_exit()。否则,当主线程退出时(要么通过调用exit,要么只调用return),那么整个进程就会死掉,这意味着所有线程也会死掉。
https://stackoverflow.com/questions/31011959
复制相似问题