[英]Simple pthread! C++
我不知道為什么這不起作用
#include <iostream>
#include <pthread.h>
using namespace std;
void *print_message(){
cout << "Threading\n";
}
int main() {
pthread_t t1;
pthread_create(&t1, NULL, &print_message, NULL);
cout << "Hello";
return 0;
}
錯誤:
[int,說明,資源,路徑,位置,類型]初始化'int pthread_create(pthread_t *,const pthread_attr_t *,void *(*)(void *),void *)'的參數3 threading.cpp threading / src第24 C / C ++問題
您應將線程main聲明為:
void* print_message(void*) // takes one parameter, unnamed if you aren't using it
因為主線程退出。
在主線程中入睡。
cout << "Hello";
sleep(1);
return 0;
POSIX標准未指定退出主線程時發生的情況。
但是在大多數實現中,這將導致所有生成的線程死亡。
因此,在主線程中,您應該等待線程死亡后再退出。 在這種情況下,最簡單的解決方案就是休眠並給其他線程執行的機會。 在實際代碼中,您將使用pthread_join();。
#include <iostream>
#include <pthread.h>
using namespace std;
#if defined(__cplusplus)
extern "C"
#endif
void *print_message(void*)
{
cout << "Threading\n";
}
int main()
{
pthread_t t1;
pthread_create(&t1, NULL, &print_message, NULL);
cout << "Hello";
void* result;
pthread_join(t1,&result);
return 0;
}
從pthread函數原型:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg);
傳遞給pthread_create的函數必須具有以下原型:
void* name(void *arg)
這對我有用:
#include <iostream>
#include <pthread.h>
using namespace std;
void* print_message(void*) {
cout << "Threading\n";
}
int main() {
pthread_t t1;
pthread_create(&t1, NULL, &print_message, NULL);
cout << "Hello";
// Optional.
void* result;
pthread_join(t1,&result);
// :~
return 0;
}
使用G ++進行編譯時,請記住放置-lpthread標志:)
連鎖。 嘗試這個:
extern "C" void *print_message() {...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.