【发布时间】:2018-05-23 12:24:59
【问题描述】:
有人能指出为什么我的代码会引发分段错误吗?很可能我在拨打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)
我应该如何解决这个错误?
【问题讨论】:
-
是的,这是什么
int* y = (int*) x;?x是整数而不是指针。 -
用-g编译,用gdb运行,它会告诉你哪里崩溃了
-
Ohh Bo Persson 明白了
-
@BoPersson 我应该改变什么?
-
"
(int*)threadid + 1;" 为什么是+1?
标签: c segmentation-fault pthreads