POSIX C Threads. Mutex example. Don't work as expected

自作多情 提交于 2019-12-05 03:33:12
pthread_create(&mythread, NULL, func, NULL);
pthread_create(&mythread, NULL, anotherFunc, NULL);

pthread_mutex_destroy(&mymutex);

You're destroying the mutex before the threads are done with it, so all bets are off. You'll probably want to pthread_join the 2 threads before destroying it.

I got few comiplation errors

  • I couldn't declare int i in for loop

  • Used an argument name arg as an argument for threads "func" and "anotherFunc"

I have used pthread_join before destroying the mutex.

In this way I am destroying my mutex "mymutex" after both threads "func" and "anotherFunc" have completed their execution

Also each threads now has their own thread id "mythread1" and "mythread2" so in this way I can use pthread_join() function for each thread

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

pthread_t mythread1, mythread2;
pthread_mutex_t mymutex;

void *anotherFunc(void *arg)
{
    pthread_mutex_lock(&mymutex);
    int i;

    for(i = 0; i < 100; i++)
        printf("anotherFunc\n");

    pthread_mutex_unlock(&mymutex);

    pthread_exit(NULL);
}

void *func(void *arg)
{
    pthread_mutex_lock(&mymutex);
    int i;
    for(i = 0; i < 100; i++)
        printf("func\n");

    pthread_mutex_unlock(&mymutex);

    pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
    pthread_mutex_init(&mymutex, NULL);

    pthread_create(&mythread1, NULL, func, NULL);
    pthread_create(&mythread2, NULL, anotherFunc, NULL);


    pthread_join(mythread1, NULL);
    pthread_join(mythread2, NULL);

    pthread_mutex_destroy(&mymutex);

   return EXIT_SUCCESS;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!