gpt4 book ai didi

c - 多线程程序中段错误的原因

转载 作者:行者123 更新时间:2023-11-30 15:18:42 24 4
gpt4 key购买 nike

以下程序因段错误而停止。当我尝试调试它时,它显示

 Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff6ff4700 (LWP 7293)]
0x0000000000400a79 in do_work(void*) ()
(gdb) bt
#0 0x0000000000400a79 in do_work(void*) ()
#1 0x00007ffff7bc4182 in start_thread (arg=0x7ffff6ff4700)
at pthread_create.c:312
#2 0x00007ffff78f0fbd in clone ()
at ../sysdeps/unix/sysv/linux/x86_64/clone.S:111

程序如下:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <unistd.h>
#include <ctime>

#define NTHREADS 3
#define iter 10
#define max_key 3
pthread_mutex_t lock[max_key];

void *do_work(void *tid)
{
int i, start, *mytid, end,rank,len,key;
double lock_var;
mytid = (int *) tid; //edit: suggested by Eric Tsui; It fixed the problem
for (i=0; i<iter; i++){
lock_var=(double)rand() / (double)RAND_MAX ;
if (lock_var<=0.5){
key = 0;
}
else if ((lock_var>0.5)&&(lock_var<=0.9)){
key = 1;
}
else {
key = 2;
}
pthread_mutex_lock (&lock[key]);
printf("I'm:%d with key:%d\n",*mytid,key);
sleep(1);
pthread_mutex_unlock (&lock[key]);

}
pthread_exit(NULL);
}



int main(int argc, char *argv[])
{
int i, start, tids[NTHREADS];
pthread_t threads[NTHREADS];
pthread_attr_t attr;
srand(time(NULL));
for (i=0;i<max_key;i++){
pthread_mutex_init(&lock[i], NULL);
}
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (i=0; i<NTHREADS; i++) {
tids[i] = i;
pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]);
}
for (i=0; i<NTHREADS; i++) {
pthread_join(threads[i], NULL);
}

printf ("Done\n");
pthread_attr_destroy(&attr);
for (i=0;i<max_key;i++){
pthread_mutex_destroy(&lock[i]);
}
pthread_exit (NULL);

}

我检查了代码,但找不到段错误的原因。谁能告诉我这段代码中段错误背后的原因。

最佳答案

myiddo_work func 应该分配输入 tid ,

void *do_work(void *tid) 
{
int i, start, *mytid, end,rank,len,key;
double lock_var;
mytid = (int *) tid; //edit: suggested by Eric Tsui; It fixed the problem
for (i=0; i<iter; i++){
lock_var=(double)rand() / (double)RAND_MAX ;
if (lock_var<=0.5){
key = 0;
}
else if ((lock_var>0.5)&&(lock_var<=0.9)){
key = 1;
}
else {
key = 2;
}
pthread_mutex_lock (&lock[key]);
printf("I'm:%d with key:%d\n",*mytid,key);
sleep(1);
pthread_mutex_unlock (&lock[key]);

}
pthread_exit(NULL);
}

关于c - 多线程程序中段错误的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31196325/

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