从fork()移动到线程

时间:2016-07-26 19:34:21

标签: c++ multithreading fork

我试图从fork()模型转移到我的应用程序中的线程。以下是我的fork()代码

的示例
#include <iostream>
#include <stdio.h>
#include <unistd.h>

void worker()
{
  std::cout<<"\nworker thread\n";
}

int start()
{
  pid_t pid;
  if((pid = fork()) < 0) {
    perror("fork");
    return -1;
  }

  if(pid != 0) {
    while(1) {
      worker();

      sleep(5);
    }
  }

}


int main()
{
  std::cout << "\nstarting...\n" << std::endl;
  start();
  std::cout << "\nend...\n" << std::endl;
  return 0;
}

我想知道这是否可以使用线程,其中main函数可以继续并调用其他函数并且线程休眠x秒并调用worker?

预期输出:

starting...


thread

end...


thread

并继续。

这是我到目前为止所做的线程代码,我遇到的问题是控件永远不会回到main,除非我加入线程,这意味着线程不再运行了。但我希望start()线程在后台继续

#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void* worker(void *data)
{
std::cout<<"\nthread\n";
  pthread_exit(NULL);
}

int start()
{

  pthread_t thread;

  while(1){

    if(pthread_create(&thread, NULL,worker,NULL)){
        printf("\nError creating thread\n");
        return -1;
      }
          sleep(10);


  }
  pthread_exit(NULL);

}


int main()
{
  std::cout << "\nstarting...\n" << std::endl;
  start();
  std::cout << "\nending...\n" << std::endl;
  return 0;

}

1 个答案:

答案 0 :(得分:1)

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;

void worker()
{
    std::cout << "Hello.\n";
}


int main()
{
    std::thread t{worker}; // spawn a thread to call worker
    std::cout << "Boo.\n";
    std::this_thread::sleep_for(std::chrono::seconds{1});
    t.join(); // wait for t to exit.
    return 0;
}