我试图掌握POSIX线程的使用情况,并创建了一个简单的程序,只需将全局变量增加10。有时,它会一直运行到很好的地方,而其他程序则会将故障随机地插入。虽然这种类型的问题似乎是线程的常规问题,但我无法理解为什么在这样一个简单的例子中会出现这种情况。我目前的想法是,由于没有加入线程,父线程可能会在结束之前结束,但是如果我试图加入,我会在第一个线程上设置错误.Join语句保留在其中,但是注释掉了。联接是否以正确的语法使用?预先形成的连接不是导致seg故障吗?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#define NUMPHILO 5
thread_t threads[NUMPHILO];  //array of threads 
pthread_mutex_t mutex;        // initialize mutex
int x = 5;          //for test
int y = 10;
int philofunct(){
    pthread_mutex_lock (&mutex);
    x = x+y;
    pthread_mutex_unlock (&mutex);
    printf("Philo fucntion x = %d\n",x);
    return x;
}
int main(){
    pthread_mutex_init(&mutex, NULL);
    for(int i = 0; i < NUMPHILO; i++){  
        printf("creating thread[%i]\n",i);
        if( pthread_create(&threads[i], NULL, (void *)philofunct(),(void *) &i) != 0)
            fprintf(stderr, "%s", strerror(errno));
//      pthread_join(threads[i],NULL);  
//      printf("Threads Joined\n");
    }
    pthread_mutex_destroy(&mutex);
    printf("Threads created\n");
}产出:
creating thread[0]
Philo fucntion x = 15
creating thread[1]
Philo fucntion x = 25
creating thread[2]
Philo fucntion x = 35
creating thread[3]
Philo fucntion x = 45
creating thread[4]
Philo fucntion x = 55
Threads created下一次跑:
creating thread[0]
Philo fucntion x = 15
creating thread[1]
Philo fucntion x = 25
creating thread[2]
Philo fucntion x = 35
Segmentation fault (core dumped)一如既往,任何帮助都是非常感谢的。
发布于 2015-03-20 23:08:50
在考虑您想要的内容之前,我看到了代码中的几个问题:
x。pthread_join。或者,您可以pthread_exit主线程,而不是让main终止(永远不要破坏互斥,这不是泄漏,因为只有一个互斥线程,并且它的生命周期随着程序的生命周期而结束),但是杀死主线程有时会产生有趣的内核“but”。https://stackoverflow.com/questions/29177083
复制相似问题