多线程初学者在这里。恰好在第5次迭代(即执行pthread_join(threadID [4],NULL)时),我的程序由于分段错误而失败。
我正在创建多个线程以从计数器变量中加减1以研究竞争条件。一切正常,直到我尝试5个线程或更多。恰好在pthread_join(threadID [4],NULL)的最后一次迭代中,它失败了,我无法确定原因。我确定问题出在哪里,因为我使用printf语句查看失败之前到达的位置。
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <stdint.h>
#include <errno.h>
#include <string.h>
#include <getopt.h>
#include <time.h>
int opt_threads;
int opt_iterations;
long nThreads;
long nIterations;
int opt_yield;
long long counter;
void add(long long *pointer, long long value) {
long long sum = *pointer + value;
if (opt_yield)
sched_yield();
*pointer = sum;
}
void *thread_worker(void * arg) {
long i;
for (i=0; i<nIterations; i++) {
add(&counter, 1);
add(&counter, -1);
}
return arg; …Run Code Online (Sandbox Code Playgroud)