c - c 中的线程,我在这里缺少什么?

标签 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

当我尝试运行它时,我根本没有得到任何输出。

最佳答案

Main 正在立即退出,因此您的进程正在立即结束。以 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);
}

关于c - c 中的线程,我在这里缺少什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20229037/

相关文章:

c++ - 发布版本中运行时间过长(调试版本正常)

c++ - 将只读数据安全地传递给新线程

c - 为什么当我从 `double` 函数返回 `void *` 时,它变得不兼容?

c - 尝试制作 RabbitMQ C-master 项目时出错

java - Executors.newFixedThreadPool 如何停止同步方法上的所有 Activity 线程

c++ - 如何关闭线程(pthread 库)?

c++ - 多线程应用程序中的段错误

c - 在 C 中使用信号量进行多线程

c - __FILE__ 没有给出完整路径

c# - 替换 AppDomain.GetCurrentThreadId();使用 ManagedThreadId