Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Problem in Threads in C++. (http://www.go4expert.com/forums/threads-cpp-t26269/)

hrdksanghavi 13Jul2011 10:54

Problem in Threads in C++.
 
Hello, I m facing problem while adding thread in my class. But if I add thread to my main function than it's working fine.

Code that is working fine is
Code:

#include <cstdlib>
#include <stdio.h>
#include "cDqu.h"
#include "cEnq.h"
#include <pthread.h>

void *Fun4Dequeu(void *threadid);

main()
{
    pthread_t thdMain;
    int t=1;
    pthread_create( &thdMain, NULL, Fun4Dequeu, (void *)t);
    pthread_join( thdMain, NULL);
    exit(0);
}
void *Fun4Dequeu(void *threadid)
{
    for(;;)
    {
        //Some code;
    }
}

But when I am trying to add a thread in my class then it gives me error

Code:

cDqu.h:36: error: argument of type ‘void (cDequeue::)(void*)’ does not match ‘void* (*)(void*)’
cDqu.h: At global scope:
cDqu.h:40: error: cannot declare pointer to ‘void’ member

the code for the class is
Code:

#include <cstdlib>
#include <fstream>
#include <time.h>
#include <ctime>
#include <unistd.h>
#include <sys/time.h>
#include <pthread.h>
#include "cEnq.h"
using namespace std;
#ifndef CDQU_H
#define    CDQU_H

std::ofstream file("output.txt", std::ios_base::out);
class cDequeue : public cEnqueue
{
public:
    pthread_t thdDqueue;
   
    int iThdRet;
    cDequeue();
    void StartThread2();
    void FunGetToken();
    void funDequeue(void *threadid);
 
};
void cDequeue::StartThread2()
{
    int t=1;
    pthread_create(&thdDqueue,NULL,funDequeue,(void *)t);
    /*above line giving problem*/
    pthread_join(thdDqueue,NULL);
       
}
    /*below line giving problem*/
void cDequeue::*funDequeue(void *threadid)
{
    cEnqueue objEnq;
    int Token=0;
    if(objEnq.qToken.empty() == false)
    {
        Token = objEnq.qToken.front();
        objEnq.qToken.pop();
    }
       
}
void cDequeue::FunGetToken()
{
        int Token=0;
        Token = FunDequeue();
        if(Token !=0)
                file<<"\tToken:"<<Token<<endl;
        else
        {
                file<<"\tQueue Empty!!!"<<endl;
        }
}
#endif    /* CDQU_H */

Please sugesst me for the same.

Regards,
Hardik

priyatendulkar 14Jul2011 15:18

Re: Problem in Threads in C++.
 
Hi,

U cannot pass a non static member function to pthread_create as non static member function includes an implicit "this" pointer.
U can consider following two solutions depending on your requirements.
1. Declare funDequeue() as static function.(No this pointer in case of static functions)
2. Write a helper function(non member ) which takes object of class cDequeue as parameter and then calls function funDequeue().
ie
void * helper(void * Obj)
{
cDequeue * ptr = (cDequeue *) Obj;
ptr -> funDequeue();

}


All times are GMT +5.5. The time now is 12:49.