[英]Stop scanf from waiting input, with another thread
我想“發送一條消息”以從線程到主程序的scanf,我在問如何賦予“ scanf”功能或“ cin”功能,以停止等待。
您通常在控制台上寫一些東西,然后按“ Enter”。 如何從另一個線程執行相同操作?
例:
int main()
{
///// Some code to make the thread work ecc
std::cin >> mystring;
std::cout << mystring; // It should be "Text into mystring";
}
// From the other thread running...
void mythread()
{
std::string test = "Text into mystring";
// Write test to scanf! How?
}
我該如何實現?
據我了解,您正在嘗試在線程之間發送信息。 正式名稱稱為Interthread Communication 。
如果要使用scanf,則應使用管道 ,這是進程之間而不是線程之間的通信工具
這是您可以在線程之間進行通信的一種方式。 閱讀器線程代表您的scanf線程。 編寫器線程代表mythread。
系統很簡單。 您有共享的內存。 當一個線程嘗試寫入它時,它將鎖定內存(在示例中為隊列)並進行寫入。 當另一個嘗試讀取它時,它再次鎖定內存並讀取它,然后將其刪除(從隊列中彈出)。 如果隊列為空,則讀取器線程將等到有人在其中寫入內容。
struct MessageQueue
{
std::queue<std::string> msg_queue;
pthread_mutex_t mu_queue;
pthread_cond_t cond;
};
{
// In a reader thread, far, far away...
MessageQueue *mq = <a pointer to the same instance that the main thread has>;
std::string msg = read_a_line_from_irc_or_whatever();
pthread_mutex_lock(&mq->mu_queue);
mq->msg_queue.push(msg);
pthread_mutex_unlock(&mq->mu_queue);
pthread_cond_signal(&mq->cond);
}
{
// Main thread
MessageQueue *mq = <a pointer to the same instance that the main thread has>;
while(1)
{
pthread_mutex_lock(&mq->mu_queue);
if(!mq->msg_queue.empty())
{
std::string s = mq->msg_queue.top();
mq->msg_queue.pop();
pthread_mutex_unlock(&mq->mu_queue);
handle_that_string(s);
}
else
{
pthread_cond_wait(&mq->cond, &mq->mu_queue)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.