PDA

View Full Version : pthread with c++ (multithreading)


spskhokhar
17th April 2012, 11:00 AM
/*
* want multi-threading in c++ code, tried boost, working perfectly.
* But want to use pthread with c++, just for fun and it works :dance:
* Following is the sample code:
*/

#include <iostream>
#include <string>
#include <cstdio>

extern "C"{
#include <pthread.h>
#include <errno.h>
}

using namespace std;

class Tester
{
private:
int value;

public:
Tester() {}
~Tester() {}
void setData(int i) {value = i;}
int getData() {return value;}
void printData()
{
int i;
for (i=value; i < (value + 10); i++) cout << "value: " << i << "\n";
}
};

void *runner(void *ptr)
{
Tester *test = static_cast<Tester*>(ptr);
test->printData();
return NULL;
}

int main(int argc, char *argv[])
{
Tester test;
pthread_t th;
test.setData(6);

if (pthread_create(&th, NULL, runner, static_cast<void*>(&test)) != 0)
{
perror("pthread_create()");
return -1;
}
pthread_join(th, NULL);
return 0;
}

marko
22nd April 2012, 01:15 AM
To compile that you'd need something like (assuming the cc file is pthread_try.cc )


g++ -lpthread -o pthread_try pthread_try.ccthen run the pthread_try executable,
you can drop the -o pthread_try option and just run "a.out" if you don't care about the resulting file name

spskhokhar
29th April 2012, 05:47 PM
thanx marko :cool:
you are right...

Iona Photos - Rundu - Monroe Photos