pThreadのメインでなぜsleep?

このQ&Aのポイント
  • Windowsとlinux環境で、pthreadをもちいて、動作確認などをしています。こちらのサンプルを下に、じっけんしていたのですが、なぜここでsleepをしなければいけないんでしょうか?
  • 実際に、削除してみると、スレッドの作業が途中で終了してしまいました。このやり方だと、作業時間がわかっている場合は、いいのですが、もしどれぐらい処理にかかるかわからない場合、困ると思います。
  • どのようにすれば、sleepを使わずに作業が終わるのをまつことができるでしょうか?
回答を見る
  • ベストアンサー

pThreadのメインでなぜsleep?

Windowsとlinux環境で、pthreadをもちいて、動作確認などをしています。 こちらのサンプルを下に、じっけんしていたのですが。 http://www.ibm.com/developerworks/jp/linux/library/l-posix3/ ここのメインのコードに, sleep(2) という表記があります。 なぜここでsleepをしなければいけないんでしょうか? 実際に、削除してみると、スレッドの作業が途中で終了してしまいました。 このやり方だと、作業時間がわかっている場合は、いいのですが、 もしどれぐらい処理にかかるかわからない場合、困ると思います。 どのようにすれば、sleepを使わずに作業が終わるのをまつことができるでしょうか? int main(void) { int x; wnode *mywork; initialize_structs(); /* CREATION */ if (create_threads()) { printf("Error starting threads... cleaning up.\n"); join_threads(); dabort(); } pthread_mutex_lock(&wq.control.mutex); for (x=0; x<16000; x++) { mywork=malloc(sizeof(wnode)); if (!mywork) { printf("ouch! can't malloc!\n"); break; } mywork->jobnum=x; queue_put(&wq.work,(node *) mywork); } pthread_mutex_unlock(&wq.control.mutex); pthread_cond_broadcast(&wq.control.cond); printf("sleeping...\n"); sleep(2); printf("deactivating work queue...\n"); control_deactivate(&wq.control); /* CLEANUP */ join_threads(); cleanup_structs(); }

質問者が選んだベストアンサー

  • ベストアンサー
  • wormhole
  • ベストアンサー率28% (1622/5658)
回答No.4

申し訳ありません。 #3は間違いです・・・ >ようするに、その場合はもしかすると、このcontrol deactivateの関数を消してしまえばいいのでしょうか。もう少し試行錯誤してみます。もしアドバイスをいただければ、助かります。 参考にしているプログラムはメインスレッドから作業スレッドに終了指示出すことで作業スレッドは終了しようとするんですから、それだといつまでも作業スレッド終了しませんけど。 使われている関数を呼ばなくするとかではできないと思いますよ。

kenpanch7
質問者

補足

コメントありがとうございます。 結局、グローバル変数を使い生成したスレッドが終了するとフラグがたつようにし、メインスレッドで無限ループで、待機してまたせることにしました。あまりスマートじゃないかもしれませんが。

その他の回答 (4)

  • wormhole
  • ベストアンサー率28% (1622/5658)
回答No.4

申し訳ありません。 #3は間違いです・・・ >ようするに、その場合はもしかすると、このcontrol deactivateの関数を消してしまえばいいのでしょうか。もう少し試行錯誤してみます。もしアドバイスをいただければ、助かります。 参考にしているプログラムはメインスレッドから作業スレッドに終了指示出すことで作業スレッドは終了しようとするんですから、それだといつまでも作業スレッド終了しませんけど。 使われている関数を呼ばなくするとかではできないと思いますよ。

  • wormhole
  • ベストアンサー率28% (1622/5658)
回答No.3

>ようするに、ここでは、2秒後に終了させたいから、終了させているわけですね。 >記事の言いたいことは理解できました。。。。 違います・・・

  • wormhole
  • ベストアンサー率28% (1622/5658)
回答No.2

sleep(2)を作業スレッドが終了するのを待つためのものと思われてるようですが「作業の作成」の所をよく読んでみてください。

kenpanch7
質問者

補足

読み直してみました。 ここですね。以下参照 次にメイン・スレッドが 2 秒間スリープに入り、その後、作業キューを非アクティブ化して、作業スレッドに対して終了するよう指示します。 ようするに、ここでは、2秒後に終了させたいから、終了させているわけですね。 記事の言いたいことは理解できました。。。。 ただし、私がしたいのは、スレッドが終了した場合は、joinをして終わらせたいのです。 ようするに、その場合はもしかすると、このcontrol deactivateの関数を消してしまえばいいのでしょうか。もう少し試行錯誤してみます。もしアドバイスをいただければ、助かります。

回答No.1

この場合の sleep(2); は、待っているというより 2なので、2秒間「他のスレッドを優先する」って意味ですね。 2秒止まるのも事実ですが。 while(1) { if (スレッドが終わったフラグ) break; } だと、他のスレッドに処理がいかないので、 逆に遅くなるので、意図的に、処理を回すために、SLEEPを 使うことが多いですよ。

kenpanch7
質問者

補足

コメントありがとうございます。要するに、実行時間がわかる場合にだけ使用する方法と思っていいでしょうか。実際、重たいタスクを走らせて、何秒かかるかわからない処理の場合は、どういった方法をとればいいでしょうか?条件変数でしょうか?

関連するQ&A

  • pthread_cond_wait 取りこぼし?

    はじめまして。 pthreadのお勉強がてら、パイプライン処理を実装してみようととりあえず実証コードを書いてみましたが、うまく意図した動きをしてくれません。 やりたいことは、処理ステージが2つあって、メインからステージ1をキックし、ステージ1は自分の処理が終わったらステージ2をキックするといった動作です。(メイン、ステージ1、ステージ2を並列に動作させたい) 取りあえず連鎖的に動作するか試したいだけなので、ステージ間のデータの受け渡しとかは、後で考えるとします。 それで、以下のような単純なコードを書きました。 期待する結果は、最後に表示される数値が 10000, 10000, 10000 になることですが、実際は、10000, 4401, 4401 のようにステージ1,2が少なくなります。 一応、それなりに調べて条件変数のセオリーに従い書いたつもりなのですが、どうしてこうなるか、ご教授ください。 test.c (空白を全角にしてあります) ------ #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> pthread_mutex_t   mutex1,           mutex2; pthread_cond_t   cond1,           cond2; int         ready1,           ready2; int         end1,           end2; int         count1,           count2; void * stage1( void *arg ) {   pthread_mutex_lock( &mutex1 );   while( 1 ) {     /* wait for my signal & job */     while ( ready1 == 0 ) {       pthread_cond_wait( &cond1, &mutex1 );     }     if ( end1 == 1 ){  /* is shutdown thread */       break;     }     /* my job. */     count1++;     /* job clear */     ready1 = 0;     /* forward next stage */     pthread_mutex_lock( &mutex2 );     ready2 = 1;     pthread_cond_signal( &cond2 );     pthread_mutex_unlock( &mutex2 );   }   pthread_mutex_unlock( &mutex1 );   return NULL; } void * stage2( void *arg ) {   pthread_mutex_lock( &mutex2 );   while( 1 ) {     while ( ready2 == 0 ) {       pthread_cond_wait( &cond2, &mutex2 );     }     if ( end2 == 1 ){       break;     }     count2++;     ready2 = 0;   }   pthread_mutex_unlock( &mutex2 );   return NULL; } int main( ) {   int     i;   pthread_t  t1,         t2;   pthread_mutex_init( &mutex1, 0 );   pthread_cond_init ( &cond1, 0 );   ready1 = 0;   end1  = 0;   count1 = 0;   pthread_create( &t1, 0, stage1, NULL );   pthread_mutex_init( &mutex2, 0 );   pthread_cond_init ( &cond2, 0 );   ready2 = 0;   end2  = 0;   count2 = 0;   pthread_create( &t2, 0, stage2, NULL );   for ( i=0; i<10000; i++ ){     pthread_mutex_lock( &mutex1 );     ready1 = 1;     pthread_cond_signal( &cond1 );     pthread_mutex_unlock( &mutex1 );   }   pthread_mutex_lock( &mutex1 );   ready1 = 1;   end1  = 1;   pthread_cond_signal( &cond1 );   pthread_mutex_unlock( &mutex1 );   pthread_join(t1, 0 );   pthread_cond_destroy( &cond1 );   pthread_mutex_destroy( &mutex1 );   pthread_mutex_lock( &mutex2 );   ready2 = 1;   end2  = 1;   pthread_cond_signal( &cond2 );   pthread_mutex_unlock( &mutex2 );   pthread_join(t2, 0 );   pthread_cond_destroy( &cond2 );   pthread_mutex_destroy( &mutex2 );   printf("%d, %d, %d\n", i, count1, count2);   return 0; } ------ gcc -o test -lpthread test.c 以上

  • pthread質問があります

    devc++を使ってpthreadの勉強をしてます pthread-win32 packageをinstall して実行をしたのですがerrorがでます 何の理由か分かりません 教えてください [Linker error] undefined reference to `_imp__pthread_attr_init' [Linker error] undefined reference to `_imp__pthread_attr_getscope' [Linker error] undefined reference to `_imp__pthread_attr_setscope' [Linker error] undefined reference to `_imp__pthread_create' [Linker error] undefined reference to `_imp__pthread_join' [Linker error] undefined reference to `_imp__pthread_exit' ld returned 1 exit status #include <pthread.h> #include <stdio.h> #define NUM_THREADS 5 void *runner(void *param); int main(int argc, char *argv[]) { int i, scope; pthread_t tid[NUM_THREADS]; pthread_attr_t attr; //get the default attributes pthread_attr_init(&attr); //first inquire on the current scope if(pthread_attr_getscope(&attr,&scope) != 0) fprintf(stderr, "Unable to get scheduling scope\n"); else { if(scope == PTHREAD_SCOPE_PROCESS) printf("PTHREAD_SCOPE_PROCESS"); else if(scope == PTHREAD_SCOPE_SYSTEM) printf("PTHREAD_SCOPE_SYSTEM"); else fprintf(stderr, "Illegal scope value.\n"); } //set the scheduling algorithm to PCS or SCS pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); //create the threads for(i=0;i<NUM_THREADS;i++) pthread_create(&tid[i],&attr,runner,NULL); //now join on each thread for(i=0;i<NUM_THREADS;i++) pthread_join(tid[i],NULL); getchar(); getchar(); return 0; } //each thread will begin control in this function void *runner(void *param) { //do some work pthread_exit(0); }

  • 条件変数を用いた有限バッファ問題を考えています。

    皆さんこんにちは。 当方、プログラミングを勉強中の学生です。 条件変数を用いた有限バッファ問題を考えております。 以下に示すソースにおいて、関数produce()は1から1000までの整数を順に生成し、関数consume()はバッファから取り出した値の合計(1から1000までの和、500500となる)を求めるようプログラミングしているつもりなのですが、コンパイルして実行すると思ったような結果となりません。 どこが間違っているかご教授いただければ幸いです。 よろしくお願い致します。 以下、ソースとなります。 #include <stdio.h> #include <pthread.h> #define N 5 int buffer[N]; int inptr = 0, outptr = 0; int count = 0; int i = 0; int j = 0; int sum = 0; pthread_cond_t full = PTHREAD_COND_INITIALIZER; pthread_cond_t empty = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; int produce (void) { i += 1; return i; } void consume (int x) { j += 1; sum += x; } void *producer(void *arg) { int data; for (;;) { if (i >= 1000) break; data = produce(); pthread_mutex_lock(&lock); while (count > N) pthread_cond_wait(&full, &lock); count = count + 1; buffer[inptr] = data; inptr = (inptr + 1) % N; pthread_mutex_unlock(&lock); pthread_cond_signal(&empty); } } void *consumer(void *arg) { int data; for (;;) { if (j >= 1000) break; pthread_mutex_lock(&lock); while (count == 0) pthread_cond_wait(&empty, &lock); count = count - 1; data = buffer[outptr]; outptr = (outptr + 1) % N; pthread_mutex_unlock(&lock); pthread_cond_signal(&full); consume(data); } } int main() { pthread_t a, b; pthread_create(&a, NULL, producer, NULL); pthread_create(&b, NULL, consumer, NULL); pthread_join(a, NULL); pthread_join(b, NULL); printf("sum = %d\n", sum); return 0; }

  • libxml2 make 失敗

    CentOS-6.2で開発用のAPサーバを構築中です。 「libxml2」をmake install したいのですが、makeが上手くいっていないように思います。 「libxml2-2.6.26」が現在インストールされているのですが、「libxml2-2.6.30」を導入しようとしています。色々調べて実施しているのですが、ログを読み取れていないので苦戦しています。。 何が原因なのでしょうか。 以下に気になる箇所のログを記載しました。 よろしくお願いいたします。 ※補足 rpmでインストールも試したのですが、それも「依存性の欠如」エラーで上手くいかない状況です。 インストールされているのに「ない」とエラーが出たりです・・・ threads.c:57: warning: redundant redeclaration of 'pthread_once' /usr/include/pthread.h:466: warning: previous declaration of 'pthread_once' was here threads.c:59: warning: redundant redeclaration of 'pthread_getspecific' /usr/include/pthread.h:1076: warning: previous declaration of 'pthread_getspecific' was here threads.c:62: warning: redundant redeclaration of 'pthread_setspecific' /usr/include/pthread.h:1080: warning: previous declaration of 'pthread_setspecific' was here threads.c:65: warning: redundant redeclaration of 'pthread_key_create' /usr/include/pthread.h:1070: warning: previous declaration of 'pthread_key_create' was here threads.c:67: warning: function declaration isn't a prototype threads.c:67: warning: redundant redeclaration of 'pthread_mutex_init' /usr/include/pthread.h:720: warning: previous declaration of 'pthread_mutex_init' was here threads.c:69: warning: function declaration isn't a prototype threads.c:69: warning: redundant redeclaration of 'pthread_mutex_destroy' /usr/include/pthread.h:724: warning: previous declaration of 'pthread_mutex_destroy' was here threads.c:71: warning: function declaration isn't a prototype threads.c:71: warning: redundant redeclaration of 'pthread_mutex_lock' /usr/include/pthread.h:732: warning: previous declaration of 'pthread_mutex_lock' was here threads.c:73: warning: function declaration isn't a prototype threads.c:73: warning: redundant redeclaration of 'pthread_mutex_unlock' /usr/include/pthread.h:743: warning: previous declaration of 'pthread_mutex_unlock' was here threads.c:75: warning: function declaration isn't a prototype threads.c:75: warning: redundant redeclaration of 'pthread_cond_init' /usr/include/pthread.h:927: warning: previous declaration of 'pthread_cond_init' was here threads.c:77: warning: function declaration isn't a prototype threads.c:431: warning: unused variable 'err' testapi.c:17978: 警告: ‘gen_xmlSchematronPtr’ defined but not used testapi.c:17981: 警告: ‘des_xmlSchematronPtr’ defined but not used testapi.c:17998: 警告: ‘gen_xmlSchematronParserCtxtPtr’ defined but not used testapi.c:33930: 警告: ‘gen_xmlSAXHandlerPtr_ptr’ defined but not used testapi.c:33933: 警告: ‘des_xmlSAXHandlerPtr_ptr’ defined but not used make[3]: ディレクトリ `/home/myapp/libxml2-2.6.30/doc/examples' から出ます make[3]: ディレクトリ `/home/myapp/libxml2-2.6.30/doc' に入ります make[3]: `all-am' に対して行うべき事はありません. make[3]: ディレクトリ `/home/myapp/libxml2-2.6.30/doc' から出ます I/O error : Attempt to load network entity http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ../doc/news.html:2: warning: failed to load external entity "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" reating gjobread make[2]: ディレクトリ `/home/myapp/libxml2-2.6.30/example' から出ます Making all in xstc make[2]: ディレクトリ `/home/myapp/libxml2-2.6.30/xstc' に入ります make[2]: `all' に対して行うべき事はありません. make[2]: ディレクトリ `/home/myapp/libxml2-2.6.30/xstc' から出ます make[1]: ディレクトリ `/home/myapp/libxml2-2.6.30' から出ます

  • 明示的なオブジェクトの削除

    以下の様なコードを用いてthreadを走らせています。 my $cond = 0; while($cond == 0){  {   my $thread;   my @threads;   my $index = 0;   while ($index < @param1){    $thread = threads->new(\&func, $param1[$index++], $param2);    push @threads, $thread;   }     sleep(1);     while (@threads > 0){    $thread = pop @threads;    $thread->join();   }  }  condcheck(); } 条件が満たされるまで、一定の処理を行うthreadを複数走らせるというものなのですが、 これを実行すると、perlの使用しているメモリがどんどん増えて行っているのを確認しました。 #@threadsや$threadのスコープが外れるようにしているのになぜ? newしたthreadオブジェクトを、明示的に削除したいのですが、どのようにすればよいでしょうか?

    • ベストアンサー
    • Perl
  • スレッドとメッセージキューに関して

    現在、下記のようなプログラムを作成しています。 内容は、メッセージキューを受信するスレッドを生成するというイメージです。 処理内容は下記のようになります。  (1)メッセージキューの生成  (2)スレッド生成(メッセージキュー受信側)  (3)スレッド停止  (4)メッセージキューの削除 しかし、(3)のスレッド停止を実施しても、(4)のメッセージキューの削除以降にて、msgrcvのエラーが出力されてしまいます。 スレッド停止を行ったことから、TestThreadは動作しなくなり、(4)のメッセージキューの削除にて、エラーともならずに終了することを望んでりますが、上手くいきません。 下記に作成しているプログラムを記載いたします。 正常終了をするには何がいけないのでしょうか? ご教授宜しくお願い致します。 [test.cc] ---------------------------------------------------------------- #include <time.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <ctype.h> #include <stdlib.h> #include <pthread.h> #include <stdlib.h> #include <sys/ipc.h> #include <sys/msg.h> // メソッドポインタ定義 typedef void (*testT); // スレッドID pthread_t threadId; // メッセージキュー識別子 int msqId; // 送受信するメッセージ struct msgbuf{ long int type; char data[BUFSIZ]; }; // テストスレッド void TestThread() { // メッセージ struct msgbuf message; while( 1 ) { printf("### TEST ###\n"); printf("msq start\n"); // 受信 if( msgrcv( msqId, &message, BUFSIZ, 0, 0 ) == -1) { printf("ERR! msgrcv errno[%d]\n", errno); continue; } printf("msq ed\n"); sleep(1); } return; } // メイン int main(int argc, char *argv[]) { // メッセージキュー識別子退避変数 int testMsqid; // スレッド操作リターン値 int status; // スレッドa用のパラメータ pthread_t thread_test; printf("### TEST START ###\n"); // メッセージキューの作成 if( (testMsqid = msgget((key_t)1111, 0666 | IPC_CREAT)) == -1 ) { printf("ERR! CREATE bkMsqId[%d]\n", testMsqid); return 1; } // メッセージキュー識別子を共通変数に設定 msqId = testMsqid; printf("msgget OK\n"); sleep(5); // スレッドを生成 status = pthread_create(&thread_test, NULL, (void*(*)(void*))TestThread, (void*)NULL); if(status!=0) { printf("pthread_create ng\n"); return 1; } printf("pthread_create OK\n"); sleep(5); // スレッド停止 status = pthread_cancel(thread_test); // スレッド停止結果 if ( status != 0 ) { printf("pthread_cancel ng\n"); return 1; } printf("pthread_cancel OK\n"); sleep(5); // メッセージキューの削除 if ( msgctl( msqId, IPC_RMID, NULL) == -1 ) { printf("msqId[%d] errno[%d]\n", msqId, errno); return 1; } printf("msgctl OK\n"); sleep(5); printf("### TEST E N D ###\n"); return 0; } ----------------------------------------------------------------

  • C言語 エンキューの問題について

    #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define MAX_QUEUE_LENGTH 11 // キューに用いる配列の⻑さ #define N 50 //乱数の範囲 typedef struct queue { int array[MAX_QUEUE_LENGTH]; int front; int rear; } Queue; Queue *init_queue() { printf("initialize queue\n"); Queue *queue = malloc(sizeof(Queue)); queue->front = 0; queue->rear = 0; return queue; } void print_test(char *line) { printf("-------------\n"); printf("test: %s\n", line); } void print_front_and_rear_index(Queue *queue) { // キューの front と rear を表示する関数 printf("front:%2d, rear:%2d\n", queue->front, queue->rear); } void print_queue(Queue *queue) { // キューの要素を front から rear まで表示する関数 } void enqueue(Queue *queue, int value) { // エンキューする関数 } void enqueue_test_items(Queue *queue, int n) { for (int i = 0; i < n; i++) { int score = rand() % N; enqueue(queue, score); } } void test_enqueue(Queue *queue) { print_test("print empty queue"); print_queue(queue); print_test("enqueue 10 items"); enqueue_test_items(queue, 10); print_test("print queue"); print_queue(queue); print_test("enqueue a item to full queue"); enqueue(queue, -1); } int main(void) { srand((unsigned)time(NULL)); // 乱数の初期化 Queue *queue = init_queue(); // キューの初期化 test_enqueue(queue); } 以下の雛形に従い,リングバッファによるキューに対して,エンキューする関数 enqueue を実装せよ. 関数 print_front_and_rear_index は,キューの front と rear を表示するための関数である. 問題に対する解答には不要であるがデバッグのために用意した. という問題なのですが関数print_queueは出来ましたが関数queueの中身がわかりませんので良ければ解答をお願いします。 自分が書いた関数print_queueは下に置いておきます 実行結果は数字以外は画像の通りになります。 void print_queue(Queue *queue) { if (queue->front == queue->rear) { printf("queue is empty\n"); } else { for (int i = queue->front; i % MAX_QUEUE_LENGTH != queue->rear; i++) { printf("queue[%2d]: %2d\n", i % MAX_QUEUE_LENGTH, } } }

  • 別ターミナルへのprintf出力

    LinuxでC言語プログラムから新しいターミナルを開き、そこにprintfで文字を出力したいのですがどうやったら良いのでしょうか?下記プログラムを作ってみましたが、新しいターミナルが開くだけで文字が出力されません #include <pthread.h> #include <stdio.h> #include <unistd.h> #include <signal.h> void* thread(void* arg) {  int pid=0;  pid = fork();  if(pid==0)  {    execlp("gnome-terminal","gnome-terminal",NULL);     printf("Hello World!!\n");  } } int main() {   pthread_t th;  void* result;   pthread_create(&th, NULL,thread, NULL);  pthread_join( th,&result); }

  • C言語 エンキューの問題について

    #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define MAX_QUEUE_LENGTH 11 // キューに用いる配列の⻑さ #define N 50 //乱数の範囲 typedef struct queue { int array[MAX_QUEUE_LENGTH]; int front; int rear; } Queue; Queue *init_queue() { printf("initialize queue\n"); Queue *queue = malloc(sizeof(Queue)); queue->front = 0; queue->rear = 0; return queue; } void print_test(char *line) { printf("-------------\n"); printf("test: %s\n", line); } void print_front_and_rear_index(Queue *queue) { // キューの front と rear を表示する関数 printf("front:%2d, rear:%2d\n", queue->front, queue->rear); } void print_queue(Queue *queue) { // キューの要素を front から rear まで表示する関数 } void enqueue(Queue *queue, int value) { // エンキューする関数 } void enqueue_test_items(Queue *queue, int n) { for (int i = 0; i < n; i++) { int score = rand() % N; enqueue(queue, score); } } void test_enqueue(Queue *queue) { print_test("print empty queue"); print_queue(queue); print_test("enqueue 10 items"); enqueue_test_items(queue, 10); print_test("print queue"); print_queue(queue); print_test("enqueue a item to full queue"); enqueue(queue, -1); } int main(void) { srand((unsigned)time(NULL)); // 乱数の初期化 Queue *queue = init_queue(); // キューの初期化 test_enqueue(queue); } 以下の雛形に従い,リングバッファによるキューに対して,エンキューする関数 enqueue を実装せよ. 関数 print_front_and_rear_index は,キューの front と rear を表示するための関数である. 問題に対する解答には不要であるがデバッグのために用意した. という問題なのですが上手くいかずに添付されている写真の実行結果通りになりません。なのでよければ解答をお願いします

  • condition_variable::wait~

    こんばんわ。タイトルに入りきらないので省略してしまいました。 condition_variable::wait_forについて質問です。 windows用のスレッドをstd::threadに置き換えてみようと思いまして、 以下のようなプログラムを書いてみました。 ---------------------------------------------------------- #include <thread> #include <mutex> #include <memory> #include <windows.h> // Sleep 用。 class CFoo { protected : struct _THREADPARAM { std::condition_variable m_cond_var_ExitQuery ; } ; // struct _THREADPARAM public : CFoo( void ){} virtual ~CFoo() { this->exitThread() ; } void Wakeup( void ) { m_lpoThread.reset( new std::thread( fnThread, std::ref( m_mutex ), &m_sThreadParam )) ; } protected : void exitThread( void ) { puts( "スレッドの終了処理をします。" ) ; m_sThreadParam.m_cond_var_ExitQuery.notify_one() ; m_lpoThread->join() ; m_lpoThread.reset() ; puts( "スレッドが終了しました。" ) ; } static int __stdcall fnThread( std::mutex& _mutex, _THREADPARAM* const lpsThreadParam ) { std::unique_lock< std::mutex > lk( _mutex ) ; std::cv_status result ; puts( "スレッドを開始します。" ) ; while( true ) { result = lpsThreadParam->m_cond_var_ExitQuery.wait_for( lk, std::chrono::seconds( 1 )) ; if( result == std::cv_status::no_timeout ) { puts( "ループを抜けます。" ) ; break ; } puts( "ループ中。" ) ; } puts( "スレッドを終了します。" ) ; return 0 ; } protected : std::mutex m_mutex ; std::shared_ptr< std::thread > m_lpoThread ; _THREADPARAM m_sThreadParam ; } ; // CFoo int main() { CFoo* foo ; foo = new CFoo() ; foo->Wakeup() ; ::Sleep( 100000 ) ; delete foo ; return 0 ; } ---------------------------------------------------------- 上記のプログラムを走らせると、「ループ中。」がずっと表示されなければならないのですが、何かのタイミングでループを抜けてしまいます。 if( result == std::cv_status::no_timeout )が真になってしまいます。 何か設定が足りないのでしょうか? ご存じの方がいらっしゃいましたら教えていただけないでしょうか。 よろしくお願いします。

専門家に質問してみよう