有人可以指出为什么我的代码会抛出分段错误吗?我很可能在致电pthread_create()
时犯了一个错误,但我没有理解错误。有人可以指出我哪里出错了吗?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
int x = 0;
int counter =
0; // This is the global variable that all the threads will increment.
pthread_mutex_t lock;
void* addcounter(void* threadid) {
pthread_mutex_lock(&lock);
int* id = (int*)threadid + 1;
int* y = (int*)x;
int total = (*id) * (*y);
int i = 0;
for (i = 0; i < total; i++) {
counter += 1;
}
pthread_mutex_unlock(&lock);
}
int main(int argc, char* argv[]) {
int thread_count = 0;
int loop_count = 0;
int expected_value = -1;
if (argc != 3) {
printf("Usage: threads <no_of_threads> <no_of_loops>\n");
exit(1);
}
thread_count = atoi(argv[1]);
loop_count = atoi(argv[2]);
x = loop_count;
// Start your implementation after this comment.
pthread_t* threads;
threads = malloc(sizeof(pthread_t) * thread_count);
int t;
int flag = 0;
for (t = 0; t < thread_count; t++) {
int* z = malloc(sizeof(int));
*z = t;
flag = pthread_create(&threads[t], NULL, addcounter, (void*)z);
}
if (flag != 0) {
printf("error in creating threads");
exit(0);
}
for (t = 0; t < thread_count; t++) pthread_join(threads[t], NULL);
// Do not change the code below this comment
return 0;
}
此代码的输出为:
Segmentation fault (core dumped)
我该如何解决此错误?
答案 0 :(得分:0)
首先,您应该使用mutex
初始化PTHREAD_MUTEX_INITIALIZER
变量。
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
或者您可以从主线程中调用pthread_mutex_init(&lock,0)
来初始化lock
。
第二件事,替换下面的陈述
int* y = (int*) x;
带
int* y = (int*) &x;
因为y
应该有valid address
,否则你以后就无法执行*y
我希望它有所帮助。
答案 1 :(得分:0)
中的多个指针问题
void* addcounter(void* threadid) {
pthread_mutex_lock(&lock);
int* id = (int*)threadid + 1; // <== A
int* y = (int*)x; // <== B
int total = (*id) * (*y); // <== C
int i = 0;
for (i = 0; i < total; i++) {
counter += 1;
}
pthread_mutex_unlock(&lock);
}
说明
int id = *(int *)threadid + 1;
int *y = (int *)x
将y
指针设置为x
... int
危险!可能是int y = x;
(?)int total = id + y;
(不需要以下循环,counter += total;
就够了