我正在尝试解决同步的一个小问题。但是当我加入线程时,我得到了第五次迭代的段错误!如果我只创建 4 个线程就完美了。
在这里,我将代码留下一些关于如何处理线程的基础知识。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
sem_t HackersEmploy_Counter;
int hackerOnBoat, employOnBoat, B, b, hackerResagado, employResagado;
sem_t Board;
int onBoatId[4];
char onBoatType[4];
sem_t Bote;
typedef struct{
FILE* log;
int ID;
}param;
void* HackerArrive(void* para){
param* var = (param*) para;
printf("Create Hacker %i\n", var->ID-1);
pthread_exit(0);
}
void* EmployeeArrive(void* para){
param* var = (param*) para;
printf("Create Employee %i\n", var->ID-1);
pthread_exit(0);
}
int main(int argc, char **argv) {
sem_init(&HackersEmploy_Counter,0,1);
sem_init(&Bote,0,4);
sem_init(&Board,0,1);
FILE* log;
log = fopen("result_simulacion.txt", "w");
int E, e=1, H, h=1, i, r;
hackerOnBoat=0; employOnBoat=0; b=1; hackerResagado=0; employResagado=0;
for (i=1; i<argc; i++){
if (strcmp(argv[i],"-h")==0){
i++;
H = atoi(argv[i]);
}
if (strcmp(argv[i],"-e")==0){
i++;
E = atoi(argv[i]);
}
if (strcmp(argv[i],"-b")==0){
i++;
B = atoi(argv[i]);
}
}
pthread_t* bank = (pthread_t*) malloc( (E+H) * sizeof (pthread_t*));
param* var = (param*) malloc( (E+H) + sizeof (param*));
for (i=0; i<H+E; i++){
r = rand() % 2;
if (r==0){
if (h<=H){
var[i].log = log;
var[i].ID = h;
pthread_create(&bank[i], NULL, HackerArrive, (void*) &var[i]);
h++;
}else{
var[i].log = log;
var[i].ID = e;
pthread_create(&bank[i], NULL, EmployeeArrive, (void*) &var[i]);
e++;
}
}else{
if (e<=E){
var[i].log = log;
var[i].ID = e;
pthread_create(&bank[i], NULL, EmployeeArrive, (void*) &var[i]);
e++;
}else{
var[i].log = log;
var[i].ID = h;
pthread_create(&bank[i], NULL, HackerArrive, (void*) &var[i]);
h++;
}
}
}
for (i=0; i<E+H; i++){
pthread_join(bank[i], NULL);
printf("join %i\n", i);
}
return 0;
}
运行:./work -h 4 -e 0 -b 1
他们运行:./work -h 5 -e 0 -b 1
如果他们将“-h”的值增加超过 4,则会收到分段错误
为什么这个?