So i am making a program with 1 main thread(my main), which creates a second one. The second one should wait for a signal and then run. Main waits of course to join.
I have a problem in understanding how my main can lock mutex, and then my thread will lock it too and wait for signal. I mean that is the "guideline" everyone gives on how to do it but I don't see how it works. Since main locks mutex, then thread will always come to a locked muted and wait for mutex to be unlocked, no? That way, signal will be sent before thread has acquired mutex and has blocked in wait(so it will never be waken). But then again it is required to lock mutex in order to wait for the variable... Pls help. This is the code, it creates a loop because threadfunction blocks in wait..
static pthread_mutex_t mtx;
pthread_cond_t cond;
void *threadfunction(void* arg){
pthread_mutex_lock(&mtx);
pthread_cond_wait(&cond,&mtx);
pthread_mutex_unlock(&mtx);
}
int main(void){
pthread_mutex_init(&mtx,NULL);
pthread_cond_init(&cond,NULL);
pthread_t tthread;
pthread_mutex_lock(&mtx);
pthread_create(&tthread,NULL,threadfunction,NULL);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
pthread_join(tthread,NULL);
}