Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
simple multithreading with semaphore posix c++
#include <iostream>
#include <unistd.h>
#include <thread>
#include <vector>
#include <signal.h>
#include <semaphore.h>
using namespace std;
vector<thread*> th;
static sem_t semaphore;
void quit(int q)
{
cout << "End" << endl;
exit(0);
}
void event(int index)
{
while(1)
{
static long count = 0;
sem_wait(&semaphore);
cout << "Thread:" << index << " Count:" << count << endl;
count++;
sem_post(&semaphore);
usleep(10000);
}
}
int main(int argc, char ** argv)
{
if(argc<2)
{
cerr << "Error: num-thread" << endl;
exit(0);
}
int MAX_THREAD=atoi(argv[1]);
signal(SIGINT,quit);
if (sem_init(&semaphore, 0, 1) == -1)
cerr << "Error: semaphore" << endl;
for(int i = 0; i < MAX_THREAD; i++)
{
thread* t = new thread(event, i);
th.push_back(t);
}
for(int i = 0; i < th.size(); i++)
th[i]->join();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.