Jishnu U Nair
Jishnu U Nair

Reputation: 520

moving from fork() to thread

I'm trying to move from fork() model to threading in my application. Following is an example of my fork() code

#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;
}

I was wondering if this is possible with threading, where the main function can continue and call other functions and the thread sleeps for x seconds and calls the worker ?

Intended output:

starting...


thread

end...


thread

and continues.

This is the threading code I have made up to now, the issue I have is that control never comes back to main unless I join the thread and that would mean the thread is not running anymore. But i want that start() thread to continue in the background

#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;

}

Upvotes: 0

Views: 145

Answers (1)

Chad
Chad

Reputation: 19052

#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;
}

Upvotes: 1

Related Questions