我正在用 C++ 开发一个 API,用于 iOS 和 Android 开发。 因此,我需要使用 pthread。
现在我有一个函数,它在序列化队列后将数据发送到服务器。
//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;
第二行会恢复第一行开始的同一个线程吗?
最佳答案
如果你真的必须使用 pthread 我认为这会起作用,但它未经测试:
#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;
}
不要忘记链接 pthread 库。没有它,它将无法工作。
但是尝试使用 std::thread。
关于c++ - 使用pthread在c++中运行后台进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30883238/