的pthread_t无法启动 [英] Pthread_t not starting

查看:185
本文介绍了的pthread_t无法启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为了了解C.It线程编程写了这个简单的例子应该写线程0。但没有输出。
这里是code。

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&pthreads.h中GT;INT I = 0;
pthread_mutex_t互斥;无效* fonction(){
    调用pthread_mutex_lock(安培;互斥);
    的printf(线程%d个\\ N,我++);
    调用pthread_mutex_unlock(安培;互斥);
    了pthread_exit(NULL);
}诠释主(){
    一个的pthread_t;
    调用pthread_mutex_init(安培;互斥,NULL);
    在pthread_create(&放大器;一,NULL,fonction,NULL);
    返回EXIT_SUCCESS;
}

有人能帮助我吗?
PS:我用这个编译

  -pthread的gcc -o test.c的测试


解决方案

插入在pthread_join(一,NULL)在pthread_create()和前返回EXIT_SUCCESS; 来保证孩子线程之前的main()收益

I wrote this brief example in order to understand thread programming in C.It was supposed to write "thread 0". But there is no output. Here is the code.

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

int i=0;
pthread_mutex_t mutex;

void * fonction(){
    pthread_mutex_lock(&mutex);
    printf("thread %d \n",i++);
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

int main(){
    pthread_t a;
    pthread_mutex_init(&mutex,NULL);
    pthread_create(&a,NULL,fonction,NULL);
    return EXIT_SUCCESS;
}

Can someone help me ? Ps : I used this to compile it

gcc -pthread test.c -o test

解决方案

Insert pthread_join(a, NULL) after pthread_create() and before return EXIT_SUCCESS; to ensure the child thread is finished before main() returns.

这篇关于的pthread_t无法启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆