繁体   English   中英

简单的pthread! C ++

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM