スレッドについてなのですが、以下のコードでsegmentation faultが起きてしまいます・・
ミューテックスがうまくいってないのでしょうか?
C
1 2#include <stdio.h> 3#include <stdlib.h> 4#include<pthread.h> 5 6struct stack { 7 int buf[128]; 8 int count; 9}; 10pthread_mutex_t mtx; 11 12void stack_init(struct stack* stk) 13{ 14 stk->count = 0; 15} 16 17void stack_push(struct stack* stk, int val) 18{ 19 stk->buf[stk->count++] = val; 20} 21 22int stack_pop(struct stack* stk) 23{ 24 if (stk->count <= 0) { 25 fprintf(stderr, "ERROR: stack is empty\n"); 26 abort(); 27 } 28 29 return stk->buf[--stk->count]; 30} 31 32void* thread_entry(void* stk){ 33 pthread_mutex_lock(&mtx); 34 for (int i=0; i < 2; i++){ 35 36 stack_push(stk,i); 37 stack_pop(stk); 38 39 } 40 pthread_mutex_unlock(&mtx); 41 return NULL; 42 43} 44 45 46int main(int argc, char* argv[]) 47{ 48 struct stack stk; 49 stack_init(&stk); 50 int er,i; 51 void* ret; 52 pthread_t tid[1]; 53 54 55 er = pthread_mutex_init(&mtx,NULL); 56 if (er != 0) goto error; 57 58 for(i=0;i<2;i++){ 59 er = pthread_create(&tid[i], NULL, thread_entry, (void *)&stk); 60 if (er != 0) goto error; 61 } 62 63 for(i=0;i<2;i++){ 64 pthread_join(tid[i], &ret); 65 } 66 67 68 69 return 0; 70 71 error: 72 fprintf(stderr,"ERROR\n"); 73 return -1; 74 75 }
回答2件
あなたの回答
tips
プレビュー