A multi threaded example with std::thread
#include <iostream>
#include <thread>
#include <mutex>
#include <ctime>
std::mutex mtx1, mtx2, mtx3;
void sleep(double sec){
clock_t st = clock();
while(((double)(clock()-st)/CLOCKS_PER_SEC) < sec);
}
struct MyRegex{
MyRegex(){
re[0].compile("\\w","i");
re[1].compile("\\d","i");
re[2].compile("\\d\\w+","i");
re[3].compile("\\d\\w\\s","m");
re[4].compile("[\\w\\s]+","m");
}
};
void thread_safe_fun1(){
MyRegex re;
std::string sub[5] = {"subject1", "123456789", "1a2b3c", "1a 2b 3c ", "I am a string"};
for(int i = 0;i<5; ++i){
re.re[i].match(sub[i], "g");
}
int c=0;
while(c++<4){
mtx2.lock();
std::cout<<"\t1";
mtx2.unlock();
sleep(0.01);
}
}
void thread_safe_fun2(){
rm.setSubject("fdsf").setModifier("g").match();
int c=0;
while(c++<4){
mtx2.lock();
std::cout<<"\t2";
mtx2.unlock();
sleep(0.009);
}
}
void thread_safe_fun3(){
rm.setSubject("fdsf").setModifier("g").match();
int c=0;
while(c++<4){
mtx2.lock();
std::cout<<"\t3";
mtx2.unlock();
sleep(0.0095);
}
}
void* thread_pseudo_safe_fun4(){
mtx1.lock();
rm.setSubject("fdsf").setModifier("g").match();
mtx1.unlock();
int c=0;
while(c++<4){
mtx2.lock();
std::cout<<"\t4";
mtx2.unlock();
sleep(0.008);
}
return 0;
}
int main(){
std::thread th1(thread_safe_fun1);
std::thread th2(thread_safe_fun2);
std::thread th3(thread_safe_fun3);
std::thread th4(thread_pseudo_safe_fun4);
th1.detach();
th2.detach();
th3.detach();
th4.join();
return 0;
}
- Author
- Md Jahidul Hamid