Pthread编程:分段错误:11使用互斥时

时间:2017-11-27 15:15:41

标签: c pthreads mutex

我正在尝试使用互斥锁来锁定代码区域。我试图发布尽可能多的代码。

//Global Variables
int sum;
long long fact=1;
pthread_mutex_t lock;
pthread_t id1,id2;

void *thread_1_And_2(void *accept_1)
{
    //Accepting Input
    int *a_ptr = (int*) accept_1;
    int a= *a_ptr;

    //Locking the resource
    pthread_mutex_lock(&lock);

    //Returning the process ID that is working right now!
    pthread_t my_current_id;
    my_current_id= pthread_self();

    if((pthread_equal(id1,my_current_id))>0)
    {

        printf("\nI am Thread 1: Processing Sum\n");

        printf("\n I am in Thread 1 \n");
        for (int i=0; i<a; i++)
        {
        sum= sum+i;
        }
    }
    else if((pthread_equal(id2, my_current_id))>0)
    {
        printf("\nI am Thread 2: Processing Factorial\n");
        if (a<0)
        {
            printf("\n Error! Factorial of Negative number not possible \n");
        }
        else
        {
            for(int i=1; i<=a; i++)
            {
            fact=fact*i;
            }
        }
    }

    //Unlocking the Mutex
    pthread_mutex_unlock(&lock);

    return 0;
}

在主要功能中,它是初始化并调用如下:

printf("\n Input for thread_1:\n");
int store_1; //= atoi(argv[1]);
printf("\nEnter number up to which you want a sum of natural numbers\n");
scanf("%d", &store_1);

printf("\nInput for thread_2:\n");
int store_2; //= atoi(argv[2]);
printf("\nEnter number whose factorial needs to be found\n");
scanf("%d", &store_2);
//Mutex Initialisation
if (pthread_mutex_init(&lock, NULL) != 0)
{
    printf("\nMutex Initialisation has Failed\n");
    return 1;
}

//Creating Threads
pthread_create(&id1, NULL, &thread_1_And_2, &store_1);//For Sum
pthread_create(&id2, NULL, &thread_1_And_2, &store_2);//For Factorial


//Joining All Threads
pthread_join(id1, NULL);
pthread_join(id2, NULL);

//Destroying the Mutex
pthread_mutex_destroy(&lock);


//Printing
printf("\n Output of Thread 1 is Sum = %d \n", sum);
printf("\n Output of Thread 2 is Factorial = %llu \n", fact);

输出:

Asking input for:
"Enter number upto which you want a sum of natural numbers"
Input Given: 5
Asking input for:
"Enter number whose factorial needs to be found"
Input Given: 3

现在屏幕正在打印:

"I am in Thread 1"
"I am in Thread 2"

暂停一段时间然后

Segmentation Fault: 11

我不知道出错的地方或地点。

0 个答案:

没有答案