- 论坛徽章:
- 24
|
zhujiang73 发表于 2016-01-27 21:39
以前写 gtkmm 程序,线程一般是这样的:现在想改用 boost 的线程。
查了些资料之后我写成这样了,写对了么?- #ifndef MCVTHREAD_H
- #define MCVTHREAD_H
- #include <boost/thread/thread.hpp>
- #include <boost/thread/mutex.hpp>
- #include <boost/thread/shared_mutex.hpp>
- #include <boost/thread/condition.hpp>
- #include <boost/function/function0.hpp>
- #include <glibmm.h>
- #include <algorithm>
- #include <functional>
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <string>
- #include <unistd.h>
- class WebWin;
- class McvThread
- {
- public:
- McvThread(){};
- ~McvThread(){};
- protected:
- Glib::Dispatcher signal_thread;
- std::queue<std::string> str_queue_events;
- //Glib::Threads::Mutex mcv_mutex;
- boost::shared_mutex shr_mutex;
- boost::condition cond;
- int num;
- public:
- void setup(WebWin *p_webwin);
- void start();
- void get_str_event(std::string &str_event);
- protected:
- void fun();
- };
- #endif // MCVTHREAD_H
复制代码- #include "webwin/webwin.h"
- #include "mcvthread/mcvthread.h"
- #include <cstdlib>
- #include <cstring>
- #include <cstdio>
- void McvThread::setup(WebWin *p_webwin)
- {
- num = 0;
- signal_thread.connect(sigc::bind<1>(sigc::mem_fun(*p_webwin, &WebWin::on_thread_signal), this));
- }
- void McvThread::fun()
- {
- for (int i=0; i<200; i++)
- {
- for (int i=0; i<10; i++) usleep(100*1000);
- //usleep(1000);
- //sleep(1);
- num++;
- char ch_text[1024];
- std::string str_text;
- shr_mutex.lock();
- if (str_queue_events.size() > 0) cond.wait(shr_mutex);
- {
- snprintf(ch_text, 1000, "Thread num : %d ", num);
- str_text = ch_text;
- snprintf(ch_text, 1000, "queue_events.size : %d ", str_queue_events.size());
- str_text += ch_text;
- str_queue_events.push(str_text);
- }
- shr_mutex.unlock();
- signal_thread();
- }
- }
- void McvThread::start()
- {
- boost::function0<void> f = boost::bind(&McvThread::fun, this);
- boost::thread thrd(f);
- }
- void McvThread::get_str_event(std::string &str_event)
- {
- shr_mutex.lock();
- //shr_mutex.lock_shared();
- if (str_queue_events.size() > 0)
- {
- str_event = str_queue_events.front();
- str_queue_events.pop();
- }
- shr_mutex.unlock();
- //shr_mutex.unlock_shared();
- cond.notify_one();
- }
复制代码- McvThread *p_mcv_thread = new McvThread();
- //p_mcv_thread->signal_thread.connect(sigc::mem_fun(*this, &WebWin::on_thread_signal));
- p_mcv_thread->setup(this);
- p_mcv_thread->start();
复制代码
- void WebWin::on_thread_signal(McvThread *p_mcv_thread)
- {
- std::string str_event = "";
- p_mcv_thread->get_str_event(str_event);
- std::cout << str_event << std::endl;
- }
复制代码 |
|