c++ - 使用pthread在c++中运行后台进程

标签 c++ multithreading pthreads background-process

我正在用 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/

相关文章:

linux - 是否有与 Windows 手动重置事件等效的 UNIX/pthreads?

c++ - 从 float 转换为自定义数字类型

c++ - Geany可以用来调试C++吗

python - 多进程程序中线程与进程的关系

c - 如何在 Mac OS X 上使用 C 实现协作轻量级线程?

java - 等待线程创建并跳过已完成执行的线程

linux - 如何防止 pthreads 中读写锁中的写入器饥饿

C++ pthread,两个线程读取一个全局变量

c++ - 指定的初始化和基类?

c++ - 使用 map 为类创建迭代器