2017-11-11 5 views
0
#include <stdio.h> 
#include <stdlib.h> 
#include <semaphore.h> 
#include <pthread.h> 

int ids = 0; 
sem_t sync; 
int idx = 0; 
int count = 0; 


void * add2(void * p_idx) { 
    int * tmp = (int *) p_idx; 
    int id = ids++; 
    sem_wait(&sync); 
    (*tmp)++; 
    count++; 
    printf("executed by %d, number is %d\n", id, *tmp); 
    sem_post(&sync); 
} 

int createThreadOutsideMain() { 
    pthread_t *outsideMain = malloc(sizeof(pthread_t)); 
    pthread_create(outsideMain, NULL, add2, (void *) &idx); 
    pthread_join(*outsideMain, NULL); 
    return 0; 
} 

void * add(void * p_idx) { 
    int * tmp = (int *) p_idx; 
    int id = ids++; 
    while(count < 10) { 
     if (count % 2 == 0) { 
      continue; 
     } 
     sem_wait(&sync); 
     (*tmp)++; 
     count++; 
     printf("executed by %d, number is %d\n", id, *tmp); 
     sem_post(&sync); 
    } 
    createThreadOutsideMain(); 
} 


int main(int argc, char * argv[]) { 
    pthread_t insideMain1, insideMain2; 
    sem_init(&sync, 0, 1); 
    pthread_create(&insideMain1, NULL, add, (void *) &idx); 
    pthread_create(&insideMain2, NULL, add, (void *) &idx); 
    pthread_join(insideMain1, NULL); 
    pthread_join(insideMain2, NULL); 
    return 0; 
} 

私はCとpthreadライブラリの新版です。一般的に以下のように記述されています。 私はスレッドを作成し、入力に応じてランタイム中にメイン関数の外にスレッドに参加したいので、ここでは、count35が奇数ならば、新しい スレッドを作成するためにif statemntを使用します。 私は0で実行されるこのC pthread_createを実行してメイン関数の外部に参加する

のような出力に、数は1で実行される0

で欲しい私は同じセマフォ&同期を使用してすべてのスレッドをしたいが、私は、コードを実行すると、それだけで立ち往生、 、数2によって実行される1

であり、数は3で実行される2

であり、数は0で実行される3

あり、数が4

0であります4によって実行

、数2によって実行される5

であり、数は0で実行6

あり、数が

が可能このアイデアは... 7 ですか?もしそうなら、私の問題はどこにありますか、あなたの助けをありがとう!

答えて

0

最初にwhileループを修正して、もう一度試してください。このループは、ifが常にtrueになる条件として不定になります。その理由は、最初のスレッドからaddメソッドを呼び出すときに、パラメータをゼロで渡すためです。まず、mutexをロックし、whileループに永久に入り込んで、2番目のスレッドがロックが解除されるのを待っています。したがって、アプリケーションは最終的に永遠にループに詰まらなくなります。パラメータを1として渡し、何が起きたかを確認します。

while(count < 10) { 
    if (count % 2 == 0) {// value of (0 % 2) == 0 always and this loop will continue for ever 
     continue; 
    } 
0
if (count % 2 == 0) { 
      continue; 
     } 

if statementが真のカウント値である場合には変更されていないとcontinue文が無限ループに

if (count % 2 == 0) { 
      count++; 
      continue; 
     } 
を取っているので、これでコードの上に置き換えます
関連する問題