2009-12-08 4 views
-1
#include<pthread.h> 
#include<stdio.h> 
#include<stdlib.h> 
#include<time.h> 
#define NUM_THREADS 8 

char *messages[NUM_THREADS]; 

struct thread_data 
{ 
    int thread_id; 
    int sum; 
    char *message; 
}; 

struct thread_data thread_data_array[NUM_THREADS]; 

void *PrintHello(void *threadarg) 
{ 
    int taskid, sum; 
    char *hello_msg; 
    struct thread_data *my_data; 

    sleep(1); 
    my_data = (struct thread_data *) threadarg; 
    taskid = my_data->thread_id; 
    sum = my_data->sum; 
    hello_msg = my_data->message; 
    printf("Thread %d: %s Sum=%d\n", taskid, hello_msg, sum); 
    pthread_exit(NULL); 
} 

int main(int argc, char *argv[]) 
{ 
pthread_t threads[NUM_THREADS]; 
//int *taskids[NUM_THREADS]; 
int rc, t, sum; 

sum=0; 
messages[0] = "English: Hello World!"; 
messages[1] = "French: Bonjour, le monde!"; 
messages[2] = "Spanish: Hola al mundo"; 
messages[3] = "Klingon: Nuq neH!"; 
messages[4] = "German: Guten Tag, Welt!"; 
messages[5] = "Russian: Zdravstvytye, mir!"; 
messages[6] = "Japan: Sekai e konnichiwa!"; 
messages[7] = "Latin: Orbis, te saluto!"; 

for(t=0;t<NUM_THREADS;t++) { 
    sum = sum + t; 
    thread_data_array[t].thread_id = t; 
    thread_data_array[t].sum = sum; 
    thread_data_array[t].message = messages[t]; 
    printf("Creating thread %d\n", t); 
    rc = pthread_create(&threads[t], NULL, PrintHello, (void *)&thread_data_array[t]); 
    if (rc) { 
    printf("ERROR; return code from pthread_create() is %d\n", rc); 
    exit(-1); 
    } 
    } 
pthread_exit(NULL); 
} 

위의 코드 조각은 내가 스레드의 pthreads 문제와 몇 가지 질문

  1. 3를하는 경우에 대한 마음에 몇 가지 질문이 초보자로서 GCC

    를 사용하여 나에게 리눅스에서 세그먼트 오류를 ​​제공합니다 스레드가 동시에 생성되고 종료해야하는 경우 먼저 생성 된 스레드가 끝에 종료됩니다.

  2. 는 오/p를 스레드 생성과 종료 프로그램마다 다를 수 있습니다 경우 왜? (나는 그들이 "그렇게 나타났습니다)
+1

내가 ", QNX의 프로그램 해봤 잘 완벽하게 작동 컴파일을 시도하고 실행 간단한 것 int main() {printf ("Hello world \ n"); return 0;} ? –

답변

2

3 만약 스레드가 동시에있는 경우 생성됩니다 그들은 끝내야 만하고, 처음에 생성 된 스레드는 마지막에 종료됩니다.

답변 : 첫 번째 스레드가 먼저 종료되어야한다는 보장은 없습니다. OS가 무엇이며 먼저 종료 할 OS를 결정해야합니다.

o/p는 스레드 작성 및 종료 프로그램마다 다를 수 있습니까? 그렇다면 그 이유는 무엇입니까? (나는 그들이 그렇게하는 것으로 나타났습니다);

답변 : 예 그들은 다릅니다. 이유는 위에서 설명한 것과 같습니다.

2

각 스레드가 예약되는 방법과시기는 OS에 따라 다릅니다. OS 코드를 자세히 살펴 보지 않고도이를 이해할 방법이 없습니다.

pthreads의 대부분의 구현에서 (모두 사용하지는 않았지만 모두 사용했습니다).
주 스레드가 종료 될 때 다른 모든 스레드가 실행을 중지하고 응용 프로그램이 종료됩니다.

따라서 주 스레드를 종료하기 전에 종료 전에 모든 하위 스레드를 기다리거나 죽여야합니다.
여기에 pthread_join()이 있습니다.

for(t=0;t<NUM_THREADS;t++) 
{ 
    void* result; 
    pthread_join(threads[t],&result); 
} 
// Now all the children are dead. 

참고 io 시스템은 스레드로부터 안전하지 않습니다.
그래서 여러 스레드가 IO에 쓰면 잠재적으로 인터리빙이 발생할 수 있습니다.

0

(나는 또한 GCC를 사용하고 있습니다) perfectely 작업 귀하의 코드 ..

출력 :.

Creating thread 0 
Creating thread 1 
Creating thread 2 
Creating thread 3 
Creating thread 4 
Creating thread 5 
Creating thread 6 
Creating thread 7 
Thread 1: French: Bonjour, le monde! Sum=1 
Thread 0: English: Hello World! Sum=0 
Thread 2: Spanish: Hola al mundo Sum=3 
Thread 4: German: Guten Tag, Welt! Sum=10 
Thread 3: Klingon: Nuq neH! Sum=6 
Thread 5: Russian: Zdravstvytye, mir! Sum=15 
Thread 6: Japan: Sekai e konnichiwa! Sum=21 
Thread 7: Latin: Orbis, te saluto! Sum=28