En fait, le scénario principal est le suivant: à partir du thread principal, deux threads sont en cours d'exécution. En utilisant la variable conditionnelle, deux threads seront exécutés et dormant, puis retourneront au thread principal. Je veux dire que je ne veux pas de modèle de sortie différent. Juste un modèle: de main-> thread1-> thread2-> main. J'ai écrit un code C thread.It montre le résultat que je veux parfois et parfois not.as par exemple, la sortie est:comment un thread peut être tué dans un autre thread
I am in thread 1
before conditional wait
I am in thread 2
before conditional release
i am again in thread 2
i am again in thread 1
main exits here
Le problème est parfois « principales sorties ici » n'a pas execute.Please aider me.It est à noter que je ne peux pas utiliser pthread_join(). mon code est donné ci-dessous
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
pthread_mutex_t gLock;
pthread_cond_t gCondition;
pthread_mutex_t mLock;
pthread_cond_t mCondition;
void initialize()
{
pthread_mutex_init(&gLock, NULL);
pthread_cond_init (&gCondition, NULL);
pthread_mutex_init(&mLock, NULL);
pthread_cond_init (&mCondition, NULL);
return;
}
void * threadOne(void * msg)
{
printf("%s \n",(char*) msg);
printf("before conditional wait\n");
pthread_mutex_lock(&gLock);
pthread_cond_wait(&gCondition,&gLock);
pthread_mutex_unlock(&gLock);
printf("i am again in thread 1\n");
pthread_mutex_lock(&mLock);
pthread_cond_signal(&mCondition);
pthread_mutex_unlock(&mLock);
}
void * threadTwo(void * msg)
{
printf("%s\n",(char*)msg);
printf("before conditional release\n");
pthread_mutex_lock(&gLock);
pthread_cond_signal(&gCondition);
pthread_mutex_unlock(&gLock);
printf("i am again in thread 2\n");
}
int main()
{
pthread_t thread1;
pthread_t thread2;
char * msg1="I am in thread 1";
char * msg2="I am in thread 2";
initialize();
pthread_create(&thread1,NULL,threadOne,(void*) msg1);
pthread_create(&thread2,NULL,threadTwo,(void*) msg2);
pthread_mutex_lock(&mLock);
pthread_cond_wait(&mCondition,&mLock);
pthread_mutex_unlock(&mLock);
printf("main exits here");
return 0;
}
Pourquoi ne pas utiliser pthread_join? C'est la manière habituelle pour un thread parent d'attendre la fin d'un enfant. – paxdiablo
Vous devriez mettre une nouvelle ligne à la fin des «sorties principales ici». Nominalement, cela pourrait être votre problème, mais il est peu probable que ce soit le problème. –
Vos fonctions de thread devraient probablement retourner une valeur - même si elle est juste 0. –