2013-06-09 1 views
0

POSIX 스레드 코딩을 위해 Windows 7 컴퓨터에서 MINGW를 사용하고 있습니다. 내 시스템에서 실행될 때 다음과 같은 출력을 보여주고있다루프에서 스레드를 생성하면 처음 2 개의 스레드가 실행되지 않습니다.

#include <stdio.h> 
#include <pthread.h> 
#include <process.h> 
#define NUM_THREADS 5 

void *PrintHello(void *threadid) 
{ 
    long tid; 
     tid = (long)threadid; 
    printf("Hello Dude...!!!\t I am thread no #%ld\n",tid); 
    pthread_exit(NULL); 
} 
int main() 
{ 
    pthread_t thread[NUM_THREADS]; 
    int rc; 
    long t; 
    for(t=0;t<NUM_THREADS;t++) 
    { 
     printf("Inside the Main Thread...\nSpawning Threads...\n"); 
     rc=pthread_create(&thread[t],NULL,PrintHello,(void*)t); 
     if(rc) 
     { 
      printf("ERROR: Thread Spawning returned code %d\n",rc); 
      exit(-1); 
     } 
    } 
    return 0; 
} 

프로그램 위 :

는 다음과 같은 간단한 코드를 고려

Inside the Main Thread... 
Spawning Threads... 
Inside the Main Thread... 
Spawning Threads... 
Hello Dude...!!!   I am thread no #0 
Inside the Main Thread... 
Spawning Threads... 
Hello Dude...!!!   I am thread no #1 
Inside the Main Thread... 
Spawning Threads... 
Hello Dude...!!!   I am thread no #2 
Inside the Main Thread... 
Spawning Threads... 

이 프로그램은 5 개 스레드를 생성하기로했다. 그러나 그것은 단지 2 개의 스레드만을 생성했습니다. 처음 2와 마지막 2 행은 pthread_create() 루틴이 호출 될 예정임을 시사합니다. 그리고 "rc"변수가 "1"이 아니기 때문에 쓰레드 생성시에 아무런 에러도 없다. 그렇지 않으면 "if (rc)"부분에 충돌했을 것이다.

그래서 어디서 오류가 있습니까? 아니면 내 Windows 머신과 관련이 있습니다.

답변

0

실제로 문제는 프로그램이 끝날 때 프로그램이 종료된다는 것입니다. 메인에서 돌아 오기 전에 그들에게 pthread_join을 보내야합니다. 다른 스레드는 전체 프로세스 공간 (및 실행 취소 된 스레드)을 가지고 메인 종료 전에 실행할 수있는 기회를 얻지 못합니다. *

가 무효로 긴 합격을하지 못 :

for(t=0;t<NUM_THREADS;t++) 
{ 
    printf("Inside the Main Thread...\nSpawning Threads...\n"); 
    rc=pthread_create(&thread[t],NULL,PrintHello,(void*)t); 
    if(rc) 
    { 
     printf("ERROR: Thread Spawning returned code %d\n",rc); 
     exit(-1); 
    } 
} 

/* add this and you're golden! */ 
for(t=0; t<NUM_THREADS;t++) { 
    pthread_join(thread[t], NULL); 
} 

다음은 내 원래의 대답은 여전히 ​​좋은 조언했다. 주소를 전달하십시오. 필요한 경우 루프를 통과 할 때마다 복사본을 만들어 전달하고 나중에 해제하십시오.

long thread_data[NUM_THREADS]; 
for(t=0;t<NUM_THREADS;t++) 
    { 
     thread_data[t] = t; 
     printf("Inside the Main Thread...\nSpawning Threads...\n"); 
     rc=pthread_create(&thread[t],NULL,PrintHello,(void*)&(thread_data[t])); 
     if(rc) 
     { 
      printf("ERROR: Thread Spawning returned code %d\n",rc); 
      exit(-1); 
     } 
    } 
+0

long을 int로 변경했지만 여전히 첫 번째 스레드가 실행되지 않고 있습니다 ... – Shantanu

+0

고마워요 ... – Shantanu

1

오류는 없습니다.

다른 스레드가 아무 것도 출력하기 전에 프로그램이 종료되고 프로그램을 종료하면 모든 스레드가 종료됩니다.

모두 제대로 마무리하려면 pthread_join 모든 스레드가 필요합니다.

+0

스레딩에 새로운 점이 있습니다 ... – Shantanu

+0

'pthread_join ', 당신은 당신이 이것을하기로되어있는 방법에 대한 많은 정보와 예제를 찾을 수있을 것입니다. 'main'의 두 번째 루프에서 생성 된 각 스레드에'pthread_join'을 호출하기 만하면됩니다. – Mat

+0

고마워 ... – Shantanu