c中的主题,我在这里缺少什么?

时间:2013-11-26 22:10:43

标签: c multithreading pthreads

我正在尝试创建一个帖子,我无法弄清楚我在这里做错了什么。这是非常基本的,我只是想确保在深入研究我将在线程中做的事情之前,我可以获得创建的线程。这是我的代码。

//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 个答案:

答案 0 :(得分:3)

Main正在退出,因此您的过程会立即消失。以pthread_join结束它以等待它们。 Here is one example我用Google搜索,其中包含以下示例代码:

#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);
}