本文介绍了线程向其他线程发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我正在用C ++编写一个程序,其中涉及两个线程.线程A从套接字读取数据,并阻塞自身,直到从套接字接收数据.线程B进行一些处理(根本不与该套接字相关),并向线程A提供一些数据.我的意思是线程B应该以某种方式使线程A中断.它应该是一个异步调用.谁能指导我在C ++中如何将一个线程异步地提供给其他线程一些输入.
谢谢,
BR
--Azam

HiI am writing one program in C++, which involves two threads. Thread A reads data from socket and it block itself until it receive data from socket. Thread B does some processing (not relevant to that socket at all) and provide some data to Thread A. I mean Thread B should intrupt Thread A some how. It should be a asynchronous call. Can anybody guide me how in C++, one thread asynchrously give some input to other thread.
Thanks,
BR
--Azam

推荐答案


class shared_data
{
    public:
        void set_it( int n )
        {
             lock l( m_ );
             data_ = n;
        }

        int get_it() const
        {
             lock l( m_ );
             return data_;
        }

    private:
        mutable mutex m_;
        int data_;
};



当您掌握了这些方法之后,就可以将其中的一种声明为全局变量(很糟糕,但可用于小型程序)或局部变量,并将其指针传递给线程函数.然后,您可以使用发送线程中的set_it()和接收线程中的get_it()进行通信.

现在是警告...

-它不会为您排队消息.如果您想要一堆消息,则必须使用上面给出的模型来实现(或者做一些低级和特定于操作系统的操作,我个人会避免像瘟疫一样)

-您的线程库(如果为C ++ 0x,则为编译器)可能具有atomic< int>为您完成所有这一切.如果是这样,请使用它!迟早所有的编译器都会有类似的好东西.

-尝试避免直接使用操作系统/POSIX接口.他们有点乖.选取类似 boost [ ^ ]为您完成繁重的任务.



When you''ve got that you can declare one of these beasts as a global (yuck but workable for small programs) or a local and pass a pointer to it to your thread functions. You can then use set_it() from the sending thread and get_it() from the receiving thread to communicate.

Now here''s the caveats...

- it won''t queue messages for you. If you want a queue of messages you''ll have to implement that using the model given above (or do something low level and OS specific that I personally would avoid like the plague)

- your threading library (or compiler if it''s C++0x) may have something like atomic<int> which does all this for you. If it does, use it! Sooner or later all compilers will have nice doodads like it.

- try and avoid using the operating system/POSIX interfaces directly. They''re a bit fiddly. Pick up a library like boost [^] to do the heavy lifting for you.



这篇关于线程向其他线程发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 22:31