Skip to content

Instantly share code, notes, and snippets.

@kashimAstro
Created October 18, 2017 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kashimAstro/2f30179a9faa7b3ba48e0e75a37c6746 to your computer and use it in GitHub Desktop.
Save kashimAstro/2f30179a9faa7b3ba48e0e75a37c6746 to your computer and use it in GitHub Desktop.
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