#スレッドの並行処理
簡単なスレッドの並行処理を実行したいのですが、以下がうまく意図した実装になりません。
1.同じ変数に対して二つのスレッドが同時にアクセスし処理をする。
2.競合状態を確認したい。
3.I/O待ちを避けるためにprintfを使わずに変数の状態を確認する。
以下コードになります。
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 11 12 13void stack_init(struct stack* stk) 14{ 15 16 stk->count = 0; 17 18} 19 20void stack_push(struct stack* stk, int val) 21{ 22 stk->buf[stk->count++] = val; 23} 24 25int stack_pop(struct stack* stk) 26{ 27 if (stk->count <= 0) { 28 fprintf(stderr, "ERROR: stack is empty\n"); 29 abort(); 30 } 31 32 return stk->buf[--stk->count]; 33} 34 35 36void* testfunc(void* stk){ 37 stk=(struct stack *)stk; 38 for(int i=0; i < 100; i++){ 39 40 stack_push(&stk, i); 41 // printf("count=%d\n",stack_pop(&stk)); 42 43 44 } 45 46} 47 48 49 50int main(int argc, char* argv[]) 51{ 52 struct stack stk; 53 pthread_t tid[2]; 54 void* retval; 55 56 for(int i=0;i<=1;i++){ 57 pthread_create(&tid[i] , NULL , testfunc ,(void*)&stk); 58 59 60 } 61 62 for (int i = 0 ; i<=1; i++){ 63 64 pthread_join(tid[i],&retval); 65 66 } 67 68 69 return 0; 70} 71 72 73
すいませんが、よろしくお願いいたします。