2017-10-10 3 views
0

Linux用Cアプリケーションのpthreadライブラリに問題があります。C Pthreadクラッシュによるアプリケーション

私のアプリケーションでは、スレッドは何度も何度も開始されます。 しかし、私はいつも、スレッドが終了するまで待ってから起動します。

スレッドがもう起動しなくなり、メモリ不足エラーが発生します。

私が見つけた解決策は、スレッドが終了した後にpthread_joinを実行することです。

スレッドが正しく終了しない理由を教えていただけますか?

ここでは、同じ問題を引き起こすコードの例を示します。 pthread_joinをが呼び出されていない場合はプロセスはスレッドのおよそ380のコールで停止:私が見つけた解決策は、スレッドが終了した後でpthread_joinを行うことです

#include <stdio.h> 
#include <stdlib.h> 
#include <stdint.h> 
#include <pthread.h> 
#include <unistd.h> 

volatile uint8_t check_p1 = 0; 
uint32_t stack_start; 

void *thread1(void *ch) 
{ 
    static int counter = 0; 
    int i; 
    int s[100000]; 
    char stack_end; 
    srand(time(NULL) + counter); 
    for (i = 0; i < (sizeof (s)/sizeof(int)); i++) //do something 
    { 
    s[i] = rand(); 
    } 
    counter++; 
    printf("Thread %i finished. Stacksize: %u\n", counter, ((uint32_t) (stack_start)-(uint32_t) (&stack_end))); 

    check_p1 = 1; // Mark Thread as finished 
    return 0; 
} 

int main(int argc, char *argv[]) 
{ 
    pthread_t p1; 
    int counter = 0; 
    stack_start = (uint32_t)&counter; // save the Address of counter 
    while (1) 
    { 
    counter++; 
    check_p1 = 0; 
    printf("Start Thread %i\n", counter); 
    pthread_create(&p1, NULL, thread1, 0); 
    while (!check_p1) // wait until thread has finished 
    { 
     usleep(100); 
    } 
    usleep(1000); // wait a little bit to be really sure that the thread is finished 
    //pthread_join(p1,0); // crash without pthread_join 

    } 
    return 0; 
} 
+0

未定義の動作:

これは、このループ内でwait(またはwaitpid、など)を使用する必要があります正確同じ理由がありますスレッド。 – EOF

答えて

0

これは、の正しいソリューションです。 である必要があります。そうしないと、スレッドリソースがリークします。

スレッドが正しく終了しない理由を教えていただけますか?

それは正しく終了を行いますが、あなたはスレッドライブラリを知るためには、それに参加する必要があります:「はい、彼は本当にこのスレッドで実行されません。もはやリソースを保持する必要が」。複数のオブジェクトに同期化されていない、非読み取り専用、非アトミックアクセスのための

while (1) { 
    int status; 
    pid_t p = fork(); 
    if (p == 0) exit(0); // child 
    // parent 
    wait(&status); // without this wait, you will run out of OS resources. 
} 
関連する問題