How to output function

How can I call my function using POSIX threads. For example, when executing code I would like thread 1 to call my function while the program is executing. Any recommendations on how to call a function when thread 1 is called during output?
</*
pthreads_demo.cpp
A very simple example demonstrating the usage of pthreads.
Compile: g++ -o pthreads_demo pthreads_demo.cpp -lpthread
Execute: ./pthreads_demo
*/

#include <pthread.h>
#include <stdio.h>
#include <iostream>
#include <string>


using namespace std;

string displayMessage1(string thread1)
{
cout << "I'm from %s function. \n";
}
string displayMessage2(string thread2)
{
cout << "I'm from thread 2 function. \n";
}

string displayMessage3(string thread3)
{
cout << "I'm from thread 3 function. \n";
}



//The thread
void *runner ( void *data )
{
string thread1, thread2, thread3;
char *tname = ( char * )data;

printf("I am %s\n", tname, thread1);
printf("I am %s\n", tname, thread2);
printf("I am %s\n", tname, thread3);

pthread_exit ( 0 );
}


int main ()
{

string thread1, thread2, thread3;
pthread_t id1, id2, id3; //thread identifiers
pthread_attr_t attr1, attr2, attr3; //set of thread attributes
char *tnames[3] = { "Thread 1", "Thread 2", "Thread 3" }; //names of threads


//get the default attributes
pthread_attr_init ( &attr1 );
pthread_attr_init ( &attr2 );
pthread_attr_init ( &attr3 );

//create the threads
pthread_create ( &id1, &attr1, runner, tnames[0] );
pthread_create ( &id2, &attr2, runner, tnames[1] );
pthread_create ( &id3, &attr3, runner, tnames[2] );

//wait for the threads to exit
pthread_join ( id1, NULL );
pthread_join ( id2, NULL );
pthread_join ( id3, NULL );

return 0;
}>
Last edited on
The only way to determine which function to call will be in the provided parameter data of runner(...).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void *runner ( void *data )
{
string thread1, thread2, thread3;
char *tname = ( char * )data;

if(0 == strcmp("Thread 1", tname)) // Note
  displayMessage1("x");
else
  ...

//printf("I am %s\n", tname, thread1);
//printf("I am %s\n", tname, thread2);
//printf("I am %s\n", tname, thread3);

pthread_exit ( 0 );
}


Please use code tags: [code]Your code[/code]
Read this: http://www.cplusplus.com/articles/z13hAqkS/

Topic archived. No new replies allowed.