You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
1.1 KiB
78 lines
1.1 KiB
#include <iostream>
|
|
|
|
#include <pthread.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
#include <string>
|
|
|
|
pthread_mutex_t print_mtx;
|
|
|
|
class IThread
|
|
{
|
|
public:
|
|
|
|
private:
|
|
|
|
virtual void* _run() = 0;
|
|
|
|
static void* _staticRun(void* context)
|
|
{
|
|
return static_cast<IThread*>(context)->_run();
|
|
}
|
|
};
|
|
|
|
|
|
|
|
void printer(std::string a)
|
|
{
|
|
pthread_mutex_lock(&print_mtx);
|
|
|
|
std::cout << a << std::endl;
|
|
|
|
pthread_mutex_unlock(&print_mtx);
|
|
}
|
|
|
|
void* foo(void* arg)
|
|
{
|
|
unsigned int i = 100;
|
|
for(;i > 0; i--){
|
|
std::string a = "foo cnt: ";
|
|
a += std::to_string(i);
|
|
printer(a);
|
|
sleep(1);
|
|
}
|
|
|
|
}
|
|
|
|
void* baa(void* arg)
|
|
{
|
|
unsigned int i = 5;
|
|
|
|
for(;i > 0; i--){
|
|
std::string a = "baa cnt: ";
|
|
a += std::to_string(i);
|
|
printer(a);
|
|
sleep(10);
|
|
}
|
|
}
|
|
|
|
int main()
|
|
{
|
|
pthread_t foo_th, baa_th;
|
|
|
|
|
|
pthread_mutex_init(&print_mtx, NULL);
|
|
|
|
pthread_create(&foo_th, NULL, foo, NULL);
|
|
pthread_create(&baa_th, NULL, baa, NULL);
|
|
|
|
|
|
pthread_join(foo_th, NULL);
|
|
pthread_join(baa_th, NULL);
|
|
|
|
|
|
return 0;
|
|
}
|
|
|