スレッドプログラムに関し質問です。
ミューテックスを使わず、スレッド二つでthread_entry関数を実行したいです。
thread_entry関数の for文の処理の部分で競合を意図的に起こし、最後stk.countを0以外の数にしたいのですが、何度実行しても0になってしまいます・・・
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}; 10 11void stack_init(struct stack* stk) 12{ 13 stk->count = 0; 14} 15 16void stack_push(struct stack* stk, int val) 17{ 18 stk->buf[stk->count++] = val; 19} 20 21int stack_pop(struct stack* stk) 22{ 23 if (stk->count <= 0) { 24 fprintf(stderr, "ERROR: stack is empty\n"); 25 abort(); 26 } 27 28 return stk->buf[--stk->count]; 29} 30 31void* thread_entry(void* stk){ 32 33 for (int i=0; i < 1000000; i++){ 34 stack_push(&stk,i); 35 stack_pop(&stk); 36 37 } 38 return NULL; 39} 40 41 42int main(int argc, char* argv[]) 43{ 44 struct stack stk; 45 stack_init(&stk); 46 int er; 47 void* ret; 48 pthread_t tid1,tid2; 49 50 er = pthread_create(&tid1, NULL, thread_entry, (void *)&stk); 51 if (er != 0) goto error; 52 er = pthread_create(&tid2, NULL, thread_entry, (void *)&stk); 53 if (er != 0) goto error; 54 55 56 pthread_join(tid1, &ret); 57 pthread_join(tid2, &ret); 58 59 printf("%d",stk.count); 60 return 0; 61 62 error: 63 fprintf(stderr,"ERROR\n"); 64 return -1; 65 66 } 67
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。