2016-07-26 94 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; 
}