Skip to content

Instantly share code, notes, and snippets.

@graphitemaster
Created September 16, 2013 08:17
Show Gist options
  • Select an option

  • Save graphitemaster/6577892 to your computer and use it in GitHub Desktop.

Select an option

Save graphitemaster/6577892 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <cstring>
#include <stdint.h>
#include <pthread.h>
#include <unistd.h> // sleep()
struct Point {
int x;
int y;
};
// a little less insane thread id management since pthread_self returns
// the lwp thread id
int thread_id = 0;
pthread_mutex_t thread_id_lock = PTHREAD_MUTEX_INITIALIZER;
int thread_id_next(void) {
int ret;
pthread_mutex_lock(&thread_id_lock);
ret = ++thread_id;
pthread_mutex_unlock(&thread_id_lock);
return ret;
}
void *PrintXY(void *data) {
Point *point = reinterpret_cast<Point*>(data);
pthread_t self = pthread_self();
sleep(point->x);
std::cout << "thread id: " << thread_id_next() << "\n";
std::cout << "lwp id: " << std::hex << *reinterpret_cast<uint64_t*>(&self) << "\n";
std::cout << point->x << "\n";
std::cout << point->y << std::endl;
return reinterpret_cast<void*>(new int(27));
}
int main(int argc, char **argv, char **envp) {
// threads
pthread_t t1;
pthread_t t2;
// points
Point p1 = { 1, 2 };
Point p2 = { 3, 4 };
// controls
int c1;
int c2;
// returns
int *r1 = 0;
int *r2 = 0;
if ((c1 = pthread_create(&t1, NULL, &PrintXY, (void*)&p1)))
std::cerr << "error = " << c1 << std::endl;
if ((c2 = pthread_create(&t2, NULL, &PrintXY, (void*)&p2)))
std::cerr << "error = " << c2 << std::endl;
// join will wait
pthread_join(t1, reinterpret_cast<void **>(&r1));
pthread_join(t2, reinterpret_cast<void **>(&r2));
std::cout << "the status of thread 1: " << std::dec << *r1 << "\n";
std::cout << "the status of thread 2: " << std::dec << *r2 << std::endl;
// free the resources
delete r1;
delete r2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment