【问题标题】:How to communicate between threads and equivalent for Waitforsingleobject()如何在线程之间进行通信以及 Waitforsingleobject() 的等价物
【发布时间】:2018-04-25 13:32:59
【问题描述】:

我刚在学校开始学习 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 : 测试 拉链传输:\250\365\277\357\376

非常感谢!

【问题讨论】:

  • 你有什么问题?
  • 嗯,第一个是为什么我的 char TT 没有正确进入第二个线程。
  • 然后,如果用户在 5 秒后没有输入一个字符 TT,程序需要不断要求用户输入一个新的字符。
  • 请不要告诉我你的导师告诉你使用pthreadstd::thread 已经成为标准 c++ 的一部分超过 6 年了...
  • 在标准中有一个名副其实的工具包我会start with those tools

标签: c++ linux multithreading waitforsingleobject


【解决方案1】:

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

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

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

看看here

【讨论】:

    猜你喜欢
    • 2011-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    相关资源
    最近更新 更多