I wrote a written program, and it does not work as I expect. I have two threads: thread triggers func and anotherThread triggers anotherFunc . What I wanted to do was when cont reaches 10 in func , anotherThread to run using pthread_cond_wait and pthread_cond_signal . The strange thing is, everything works fine if I uncomment the sleep(1) . I'm new to threads, and I followed the tutorial here , and if I comment on the sleep line in their example, it will also break.
My question is, how can I do this work without sleep() calls? And what happens if in my code both func reaches pthread_mutex_lock after anotherFunc ? How can I control these things? This is my code:
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <pthread.h> pthread_mutex_t myMutex; pthread_cond_t cond; pthread_attr_t attr; int cont; void *func(void*) { printf("func\n"); for(int i = 0; i < 20; i++) { pthread_mutex_lock(&myMutex); cont++; printf("%d\n", cont); if(cont == 10) { printf("signal:\n"); pthread_cond_signal(&cond); // sleep(1); } pthread_mutex_unlock(&myMutex); } printf("Done func\n"); pthread_exit(NULL); } void *anotherFunc(void*) { printf("anotherFunc\n"); pthread_mutex_lock(&myMutex); printf("waiting...\n"); pthread_cond_wait(&cond, &myMutex); cont += 10; printf("slot\n"); pthread_mutex_unlock(&myMutex); printf("mutex unlocked anotherFunc\n"); printf("Done anotherFunc\n"); pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t thread; pthread_t anotherThread; pthread_attr_init(&attr); pthread_mutex_init(&myMutex, NULL); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_cond_init(&cond, NULL); pthread_create(&anotherThread, &attr, anotherFunc, NULL); pthread_create(&thread, &attr, func, NULL); pthread_join(thread, NULL); pthread_join(anotherThread, NULL); printf("Done MAIN()"); pthread_mutex_destroy(&myMutex); pthread_cond_destroy(&cond); pthread_attr_destroy(&attr); pthread_exit(NULL); return 0; }
Sorry for the long post, but I'm new to streams and I'm ready to learn. Also do you know good links or courses / tutorials on streams and networks on Linux? I want to learn how to create a chat client, and I heard that for this I need to know the topics and networks. The problem is that I do not know very well that what I learn is good, since I do not know what I need to know.
Thank you very much:)
source share