【发布时间】:2020-10-06 13:12:31
【问题描述】:
我正在学习使用 c++ 进行多线程编码。我需要做的是不断从键盘读取单词,并将其传递给数据线程进行数据处理。我使用 global 变量 word[] 来传递数据。当 word[0] != 0 表示来自键盘的新输入。 数据线程会在读取数据后将word[0]设置为0。有用!但我不确定它是否安全,或者有更好的方法来做到这一点。这是我的代码:
#include <iostream>
#include <thread>
#include <cstdio>
#include <cstring>
using namespace std;
static const int buff_len = 32;
static char* word = new char[buff_len];
static void data_thread () { // thread to handle data
while (1)
{
if (word[0]) { // have a new word
char* w = new char[buff_len];
strcpy(w, word);
cout << "Data processed!\n";
word[0] = 0; // Inform the producer that we consumed the word
}
}
};
static void read_keyboard () {
char * linebuf = new char[buff_len];
thread * worker = new thread( data_thread );
while (1) //enter "end" to terminate the loop
{
if (!std::fgets( linebuf, buff_len, stdin)) // EOF?
return;
linebuf[strcspn(linebuf, "\n")] = '\0'; //remove new line '\n' from the string
word = linebuf; // Pass the word to the worker thread
while (word[0]); // Wait for the worker thread to consume it
}
worker->join(); // Wait for the worker to terminate
}
int main ()
{
read_keyboard();
return 0;
}
【问题讨论】:
标签: c++ multithreading