This is an example of the CEventServer and the CThreadServer classes working together.
This example shows how the both servers can work together to synchronize several threads of execution. This example create two threads that communicate to each other using events in order to synchronize their execution.
The main program creates all the events and threads, and then start the execution of the threads, and waits for their termination. The output of this example should be somthing like this:
* Thread1 - Waiting for event event1
* Thread2 - Sending event event1
* Thread2 - Waiting for event event2
* Thread1 - Event event1 received
* Thread1 - Sending event event2
* Thread1 - Sending event event3
* Thread1 - Ending
* Thread2 - Event event2 and event3 received
* Thread2 - Ending
* End of the program
*
After the first message, and before the reception of the activation of the second and thirth events, the program halts for a few seconds in the wait functions.
#include "eventserver.h"
#include "threadserver.h"
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include "log.h"
const std::string thread1_id="thread1";
const std::string thread2_id="thread2";
const std::string event1_id="event1";
const std::string event2_id="event2";
const std::string event3_id="event3";
void *thread1_function(void *param)
{
std::list<std::string> event_list1;
CLog thread_log(
"thread1");
event_list1.push_back(event1_id);
std::cout << "Thread1 - Waiting for event " << event1_id << std::endl;
thread_log.
log((
const std::string)
"Thread1 - Waiting for event" + event1_id);
std::cout << "Thread1 - Event " << event1_id << " received" << std::endl;
pthread_exit(NULL);
}
void *thread2_function(void *param)
{
std::list<std::string> event_list2;
CLog thread_log(
"thread2");
event_list2.push_back(event1_id);
std::cout << "Thread2 - Waiting for event " << event1_id << std::endl;
thread_log.log((const std::string)"Thread2 - Waiting for event" + event1_id);
std::cout << "Thread2 - Event " << event1_id << " received" << std::endl;
pthread_exit(NULL);
}
int main(int argc,char *argv[])
{
main_log.log("Creating events ...");
main_log.log((const std::string)"Creating threads ...");
main_log.log((const std::string)"Starting thread 1 ...");
sleep(3);
main_log.log((const std::string)"Starting thread 2 ...");
sleep(3);
sleep(2);
sleep(2);
std::cout << "End of the program" << std::endl;
main_log.log((const std::string)"End of the program");
}