У меня есть два потока: поток запускает func и другой поток запускает другойFunc< /код>. Я хотел сделать так, чтобы cont достигал значения 10 в func, чтобы запускался другой поток с использованием pthread_cond_wait и pthread_cond_signal. Странно то, что все работает нормально, если я раскомментирую строку Sleep(1). Я новичок в потоках, и я следил за руководством здесь, и если я прокомментирую строку сна в их примере, она также сломается.
Мой вопрос в том, как я могу сделать это работает без вызовов Sleep()? А что произойдет, если в моем коде обе функции func достигнут pthread_mutex_lock после другой функции? Как я могу контролировать эти вещи? Это мой код:
Код: Выделить всё
#include
#include
#include
#include
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;
}
Большое спасибо
Подробнее здесь: https://stackoverflow.com/questions/101 ... s-expected
Мобильная версия