[英]Running background process in c++ using pthread
I am developing an API in c++ to be used in iOS and Android development.我正在用 C++ 开发一个 API,用于 iOS 和 Android 开发。 Hence, I need to use pthread.因此,我需要使用 pthread。
Now I have a function, which sends data to the server after serialization of a queue.现在我有一个函数,它在队列序列化后将数据发送到服务器。
//include headers here
void sendToServer(queue q) {
/*
send the whole queue to server after serialization
pop the queue
*/
}
which is called by这被称为
// headers
void log (data)
{
while(1)
{/*
add data to queue q
*/
if(num_nodes>=threshold || duration > interval)
sendToServer(q);
//apply thread wait condition
}
}
If i want to make a separate thread for log which runs in the background, can I implement a singleton class with a method get_instance which starts a thread with log如果我想为在后台运行的 log 创建一个单独的线程,我可以使用 get_instance 方法实现一个单例类,该方法用 log 启动一个线程
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;
}
}
So, next time in my test function, when i do:所以,下次在我的测试功能中,当我这样做时:
C::get_instance(); //C::get_instance->signal_thread_to_resume;
will the second line resume the same thread started in the first line?第二行会恢复在第一行开始的同一个线程吗?
If you really have to use pthread I think this will work, but it is untested:如果你真的必须使用 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;
}
Don't forget to link with the pthread libary.不要忘记链接 pthread 库。 Without it, it will not work.没有它,它将无法工作。
But try to use std::thread.但是尝试使用 std::thread。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.