2015-06-17 12 views
2

我正在开发一个用于iOS和Android开发的C++ API。 因此,我需要使用pthread。使用pthread在C++中运行后台进程

现在我有一个函数,它在队列序列化后将数据发送到服务器。

//include headers here 
void sendToServer(queue q) { 
    /* 
    send the whole queue to server after serialization 
    pop the queue 
    */ 
} 

这是由

// headers 
void log (data) 
{ 
    while(1) 
    {/* 
    add data to queue q 
    */ 
    if(num_nodes>=threshold || duration > interval) 
    sendToServer(q); 
    //apply thread wait condition 
    } 
} 

如果我想为日志一个单独的线程运行在后台调用,我可以实现一个方法get_instance一个单类启动一个线程使用日志

class C 
{ 
    private: 

    C(); 
    /*disallow copy constructor and assignment operator*/ 
    static C* singleton_inst; 
    pthread_t t; 
    void sendToServer(queue q); 

    public: 

    void* log(void*); 
    static C* get_instance() 
    { 
     if(singleton_inst==NULL) 
     { 
     pthread_create(t, NULL, log, NULL); 
     singleton_inst= new C(); 
     } 
     return singleton_inst; 
    } 
} 

所以,在我的测试功能下一次,当我这样做:

C::get_instance(); //C::get_instance->signal_thread_to_resume;

第二行是否会恢复第一行开始的同一个线程?

+1

为什么你不能使用'std :: thread'?如果你有C++ 11,你可能要考虑'std :: packaged_task','std :: async'和'std :: future' /'std :: promise'。 – kfsone

+0

我的同事告诉我,与其他人存在一些跨平台问题。所以,我正在购买他们的话。老实说,我也没有使用过其他人。 –

+0

'std ::'选项是标准库函数,所以它们通常是...标准。你的同事可能只是不熟悉C++ 11。 – kfsone

回答

1

如果你真的要使用并行线程,我认为这会工作,但它是未经测试:

#include <iostream> 
#include <pthread.h> 
using namespace std; 

//include headers here 
/*the called function must be void* (void*) */ 
/* so you have to cast queue*/ 
void* sendToServer(void* q) { 
    /* 
    send the whole queue to server after serialization 
    pop the queue 
    */ 
} 

pthread_t thread1; 

// headers 
void log (char* data) 
{ 

    // create the thread 
    int th1 = pthread_create(&thread1, NULL, sendToServer, (void*) data); 
} 

int main() { 
    log((char*)"test"); 
    /* Wait till threads are complete before main continues. Unless we */ 
    /* wait we run the risk of executing an exit which will terminate */ 
    /* the process and all threads before the threads have completed. */ 
    pthread_join(thread1, NULL); 
    return 0; 
} 

不要忘了与并行线程libary链接。没有它,它将无法工作。
但尝试使用std :: thread。

+0

我不认为这会在后台运行该进程。 首先,我想为了让函数永久运行在后台,需要在函数内部有一个无限循环。 其次,您在日志中创建了线程,这意味着每次调用日志时,都会创建一个带有sendToServer的新线程。而且你从未摧毁过线程。它冒着风险。 第三,如果sendToServer和log是不同类的成员呢? –

+0

我向你展示了pthread的基本功能。 在这种情况下,sendToServer函数位于一个额外的线程中。如果你不想在后台获得另一个功能,你必须以类似的方式来完成。 当然,您可以在后台函数中进行循环,例如检查作业列表。此列表可以是[std :: function]的[std :: vector](http://en.cppreference.com/w/cpp/container/vector)(http://en.cppreference.com/w/ CPP /效用/功能/函数) – StheKing

+0

@VShreyas我想你不得不作出详细的答案,提出详细的问题,所以显示你的类的构造。 – StheKing