gpt4 book ai didi

c++ - 如何在线程和 Waitforsingleobject() 的等价物之间进行通信

转载 作者:太空宇宙 更新时间:2023-11-04 12:07:42 34 4
gpt4 key购买 nike

我刚开始在学校学习 C++,我正在尝试同时学习 Linux 和 Windows。所以这是我的代码和练习。问题是我不知道如何安排线程再次运行的时间,而且每当我运行它时,我都得不到正确的字符。

#include <iostream>
#include <cstdlib>
#include <pthread.h>


using namespace std;
bool t;

#define NUM_THREADS 3

void *Saisie(void *PT)
{
char TT[150];
cout << "Entrez une chaîne de caractères :" <<endl;
cin >> TT;
t = true;
pthread_exit(NULL);
}

void *Visualisation(void *PT)
{
cout<<"La chaine transmise est :" << &*(char*)PT <<endl;
pthread_exit(NULL);
}

int main ()
{
pthread_t TH1;
pthread_t TH2;
char TT[150];
t = false;

while (t == false){
pthread_create(&TH1,NULL,Saisie,&TT); // Création du thread TH1
pthread_join(TH1,NULL);
}
if (t == true){
pthread_create(&TH2,NULL,Visualisation,&TT); // Création du thread TH2
pthread_join(TH2,NULL);
}

cout << "\nFin du programme – saisir une lettre pour fermer\n";
cin >> TT;
}

我的输出如下:

Entrez une chaîne de caractères : 测试La chaine transmise est :\250\365\277\357\376

非常感谢!

最佳答案

同步您的线程并使用 C++ 标准提供的库。这样您的代码就可以移植。

使用 pthread 库并不比上述选项更可取。有一个适用于 Windows 的 pthread 实现,但是当您可以使用 C++ 标准提供的内容只编写一次时,为什么还要麻烦呢。

要回答您的特定查询,您可以使用 sleep 原语,或者如果您需要等待某个条件,则使用条件变量

看看here

关于c++ - 如何在线程和 Waitforsingleobject() 的等价物之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50023710/

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