gpt4 book ai didi

c++ - 为什么在所有 5 个线程都为多线程 C++ 餐饮哲学家之谜运行后,我只得到线程 # 0 的无限循环

转载 作者:行者123 更新时间:2023-11-28 06:06:36 25 4
gpt4 key购买 nike

现在所有 5 个线程都在运行。但是在第一次运行 5 个线程之后。只有第一个线程(线程#0)运行无限阻塞其余线程。我只看到线程 # 0 空闲(等待)和消耗(吃)并再次进入无限循环,其他 4 个线程在第一轮后没有机会。

struct sem_t_ * sem[5];
struct sem_t_ * lock;

class Phil
{
public:
Phil()
{
isThinking = isEating = 0;
mId = 0;
}

//~Phil();
bool isThinking;
bool isEating;

int mId;

void setID(int id)
{
mId = id;

}

void think()
{
isThinking = 1;
isEating = 0;

cout<<"Thread "<<mId<<" is idle!.\n";


}

void eat()
{

isThinking = 0;
isEating = 1;

cout<<"Thread "<<mId<<" is consuming!.\n";

}
};


void pause()
{
Sleep(1000);
}

Phil* pArray = new Phil[5];

void* thread_Create(void*param)
{
int value = 0;
int* id = (int*)param;

for(;;)
{

cout<<"Thread Id = "<<*id<<" running.\n";

pArray[*id].think();

sem_wait(&lock);

int left = *id;
int right = (*id)+1;
if( right > 4) right = 0;

//cout<<"Left = "<<left<<" Right = "<<right<<endl;

sem_getvalue(&sem[left],&value) ;

//cout<<"Left Value = "<<value<<endl;

if( value != 1 )
{
sem_post(&lock);
continue;
}

if( value != 1 )
{
sem_post(&lock);
continue;
}

sem_wait(&sem[left]);
sem_wait(&sem[right]);

pArray[*id].eat();
sem_post(&sem[left]);
sem_post(&sem[right]);

sem_post(&lock);

pause();
}
return 0;
}

void main(void)
{
int i = 0;

for(i=0; i< 5;i++)
{
pArray[i].setID(i);
sem_init(&sem[i],0,1);

}

sem_init(&lock, 0, 5);

pthread_t threads[5];

for(i=0; i< 5;i++)
{
pthread_create(&threads[i],NULL,thread_Create, (void*)&i);
pause();

}

for(i=0; i< 5;i++)
{

pthread_join(threads[i], NULL); //Main thread will block until child threads exit!
}


for(i=0; i< 5;i++)
{
sem_destroy(&sem[i]);
}

sem_destroy(&lock);

}

最佳答案

您的问题出在这一行:

pthread_join(threads[i], NULL); //Main thread will block until child threads exit!

它完全按照您的评论所说 - 您的主线程创建一个线程(线程 0),然后阻塞直到线程 0 完成,但它永远不会这样做。所以你的主程序永远不会创建更多的线程。

解决方案是将 pthread_join 调用移动到另一个循环中。即首先创建所有线程,然后等待它们全部完成。

关于c++ - 为什么在所有 5 个线程都为多线程 C++ 餐饮哲学家之谜运行后,我只得到线程 # 0 的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32260532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com