Log functions in a multi-threaded environment should be able to synchronize, multiple threads at the same time log output to the same log file, every time the log records should be kept intact, that is, the log function to achieve synchronous processing. The following example uses Poco multithreaded programming to start 200 child threads at a time, and each child thread function is responsible for writing its own log contents to the log file.
Include Files and namespaces
#include "Poco/thread.h"
#include "poco/runnable.h"
Using Poco::thread;
Using Poco::runnable;
#include "Poco/thread.h"
#include "poco/runnable.h"
Using Poco::thread;
Using Poco::runnable;
Multithreading control code, using Poco::thread
void Threaddemo () {//create log logger& logtest = Logger::get ("Testlogger"); Autoptr<consolechannel> Pchannel (new Consolechannel); Logtest.setlevel (poco::message::P rio_debug); Logtest.setchannel (Pchannel); #define Trd_num Thread Trd[trd_num]; Worker Worker[trd_num]; Start Trd_num threads for (int i = 0; i < trd_num;i++) {Worker[i].setlogger (logtest); Trd[i].start (worker[i));//wait for all threads to end for (int i= 0; i < trd_num;i++) {trd[i].join ();} #undef Trd_num}
The child thread uses poco::runnable and writes text to the log file via logger
Thread function class Worker:public Runnable {public:void run () {message msg; Patternformatter FMT; string result; Msg.setsource ("Worker"); Fmt.setproperty ("pattern", "[%y-%m-%d%h:%m:%s%n:%p:%s:%i]-%t"); Fmt.format (Msg,result); result = "Run function"; M_plog->information (result); } void Setlogger (logger& Logger) {m_plog = &logger;} private:logger* m_plog; };