gpt4 book ai didi

c - C 中 pthread 和并发的段错误

转载 作者:行者123 更新时间:2023-11-30 14:46:20 25 4
gpt4 key购买 nike

我正在尝试创建一个线程,等待分配任务然后执行它,但是我遇到了麻烦。

#include "dispatchQueue.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

pthread_mutex_t mutex;
pthread_cond_t cond;
task_t *task;

void test1() {
sleep(1);
printf("test1 running\n");
}

void* do_stuff(void *args) {
printf("in do stuff\n");
pthread_mutex_lock(&mutex);
printf("after do stuff has lock\n");
task_t *task = (task_t *)args;
(task->work) (task->params);
pthread_mutex_unlock(&mutex);

}

int main(int argc, char** argv) {
pthread_t thread;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_mutex_lock(&mutex);
printf("after main gets lock\n");
pthread_create(&thread, NULL, do_stuff, task);
task = task_create(test1, NULL, "test1");
pthread_mutex_unlock(&mutex);
printf("after main unlocks \n");

pthread_join(thread, NULL);
}

上面的代码会产生段错误,但是如果我切换 pthread_create 和 task = task_create() 行,那么它就可以正常工作。我对C一点也不熟悉,所以我想知道这是为什么?

这就是创建任务的方式(如果有帮助的话),此时我很确定这是我使用 pthreads 的方式的问题。

task_t *task_create(void (*work)(void *), void *param, char* name) {
task_t *task_ptr = malloc(sizeof(task_t));
if (task_ptr == NULL) {
fprintf(stderr, "Out of memory creating a new task!\n");
return NULL;
}
task_ptr->work = work;
task_ptr->params = param;
strcpy(task_ptr->name, name);
return task_ptr;
}

最佳答案

pthread_create(&thread, NULL, do_stuff, task);
task = task_create(test1, NULL, "test1");

您正在向线程传递垃圾。您尚未将 task 设置为此处的任何特定值,但您已将其作为参数传递给线程。

void* do_stuff(void *args) {         // *** args is garbage here
printf("in do stuff\n");
pthread_mutex_lock(&mutex);
printf("after do stuff has lock\n");
task_t *task = (task_t *)args; // ** So task is garbage here
(task->work) (task->params);
pthread_mutex_unlock(&mutex);
}

在这里,您可以从 args 初始化 task。但是 args 有一个垃圾值。

如果您有某种集合要跟踪线程将要执行的任务,则必须向线程传递一个参数,以使其能够可靠地找到该集合。在这种特殊情况下,&task 可以工作。

关于c - C 中 pthread 和并发的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52347412/

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