很抱歉,我是c ++和linux的新手,之前我还没有看到过Segmentation故障。我可以成功编译该文件,但它只输出Segmentation fault。
我尝试了谷歌分段错误,但仍然不知道如何修复我的代码。
希望有人可以通过专门说明我犯错误的行来拯救我并告诉我是什么错误。 我很感激!非常感谢!
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <cstring>
#include <semaphore.h>
using namespace std;
#define NUM_THREADS 36
#define MAX 36
char matrix[6][6]; //result sheet
//queue elements
char queue[MAX], head=0, tail=0;
int row=0,col=0;
int runtime=1; // track the number of times we have run the dispatch
funciton
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void dispatch(){
row = runtime / 6;
sleep(1); //wait 1 second to generate column number
col = runtime % 6 - 1;
if (runtime % 6 == 0)
col = 5;
runtime++;
}
void enqueue(char c){
queue[tail] = c;
tail = (tail+1)%MAX ;
}
char dequeue(){
char temp = queue[head];
head = (head+1)%MAX ;
return temp;
}
//master thread
void *qcTask(void *args) {
//simulate product convey delay
sleep(1);
pthread_mutex_lock(&mutex);
dispatch();
sleep(rand()%6+5);
if(rand()%100<90)
enqueue('Q');
else
enqueue('U');
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main (int argc, char* argv[]){
int input = atoi(argv[1]);
//error handling
if(argc!=2 || input < 0 || input>36){
cout<<"Input is illegal!";
}
else{
pthread_t threads[input];
int rc, i, count = 0;
srand(time(NULL));
for(i = 0;i<input;i++){
rc = pthread_create(&threads[i], NULL, qcTask, NULL);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
for (i = 0; i < input; i++){
rc = pthread_join(threads[i], NULL);
if (rc){
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
}
//initize matrix with default value 'i'
for (int i = 0; i < 6; i++){
for (int j = 0; j < 6; j++){
matrix[i][j] = 'I';
}
}
//fill the result sheet
for(int i=0;i<6;i++){
for (int j = 0; j < 6; j++){
matrix[i][j]=dequeue();
}
}
for (int i = 0; i < 6; i++){
for (int j = 0; j < 6; j++){
cout << matrix[i][j];
if (matrix[i][j] == 'U')
count++;
}
cout << endl;
}
cout << count << " products are unqualified.";
pthread_exit(NULL);
}
}
答案 0 :(得分:2)
分段错误(segfault / SIGSEGV)仅表示操作系统检测到您的程序试图访问其分配的地址空间之外的内存。可能有许多原因(几乎总是由 代码中的错误引起)。 例子包括:
取消引用未初始化的指针
写过数组(或其他容器)的末尾
取消引用nullptr
写入或阅读免费记忆
还有更多..