2016-07-26 58 views
0

我试图从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; 
} 

我在想,如果这是可能的线程,其中主要的功能可以继续,并呼吁其他功能和线程睡眠x秒并呼吁工人的我fork()代码的例子吗?

预期输出:

starting... 


thread 

end... 


thread 

,并继续。

这是我现在编写的线程代码,我遇到的问题是控制永远不会回到主线程,除非我加入线程并且这意味着线程不再运行。但我想,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; 

} 
+0

我不理解你的意思。您是否曾尝试将该程序翻译为单一进程,多线程方法? –

+0

是的,我可以发布该代码 –

+0

是的,你写了一个函数,while(1){worker();睡眠(5); }'并在创建线程时指定它作为参数。 std :: thread'文件的哪一部分有问题? –

回答

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