2013-11-26 80 views
0

我想創建一個線程,並且我無法弄清楚我在這裏做錯了什麼。這是非常基本的,我只是想確保我可以在創建線程之前創建線程中要做的事情。這是我的代碼。c中的線程,我在這裏錯過了什麼?

//prog.c 
#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include <ctype.h> 
#include <pthread.h> 
#include <stdbool.h> 
#include <unistd.h> 

int threadCount =0; //Global variable to hold our thread counter 

//this is the function that gets called when a thread is created 
void *threadCreate(void* arg){ 
    printf("Thread #%d has been created\n", threadCount); 
    threadCount++; 
    int param = (int)arg; 

    printf("We were sent: %d\n", param); 
    printf("Now the thread will die\n"); 
    threadCount--; 
    pthread_exit(NULL); 
} 

//main 
int main(int argc, char *argv[]){ 
    pthread_t tid; 
    int numski = 50; 
    int res; 
    res = pthread_create(&tid, NULL, threadCreate, (void*)numski); 
    if (res){ 
     printf("Error: pthread_create returned %d\n", res); 
     exit(EXIT_FAILURE); 
    } 
    return 0; 
} 

我使用下面的命令編譯:

gcc -Wall -pthread -std=c99 prog.c -o Prog 

當我嘗試運行它,我得到任何輸出。

+1

你錯過接下來的事情就是在你進入全局變量'threadCount'互斥。 – pilcrow

回答

3

主要馬上就要退出,因此你的程序馬上就要死了。用pthread_join結束等待它們。 Here is one example我一派,其中包含下面的代碼示例:

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

void *print_message_function(void *ptr); 

main() 
{ 
    pthread_t thread1, thread2; 
    const char *message1 = "Thread 1"; 
    const char *message2 = "Thread 2"; 
    int iret1, iret2; 

    /* Create independent threads each of which will execute function */ 

    iret1 = pthread_create(&thread1, NULL, print_message_function, (void*) message1); 
    iret2 = pthread_create(&thread2, NULL, print_message_function, (void*) message2); 

    /* Wait till threads are complete before main continues. Unless we */ 
    /* wait we run the risk of executing an exit which will terminate */ 
    /* the process and all threads before the threads have completed. */ 

    pthread_join(thread1, NULL); 
    pthread_join(thread2, NULL); 

    printf("Thread 1 returns: %d\n",iret1); 
    printf("Thread 2 returns: %d\n",iret2); 
    exit(0); 
} 

void *print_message_function(void *ptr) 
{ 
    char *message; 
    message = (char *) ptr; 
    printf("%s \n", message); 
} 
相關問題