【问题标题】:Thread using emscripten使用 emscripten 的线程
【发布时间】:2014-12-14 20:52:35
【问题描述】:

我正在尝试将线程与 Emscripten 一起使用,但我不明白它是如何工作的。我读过一些关于网络工作者的文章,但我不确定。

当我查看“测试”文件夹时,I can see pthread stuff

我正在使用“std::thread”并收到以下错误:

unresolved symbol: pthread_create

我必须使用网络工作者而不是默认线程吗?

谢谢!

【问题讨论】:

标签: pthreads emscripten


【解决方案1】:

正在添加对 pthread 的支持,并且已经可以通过一些设置来使用。由于 std::thread 在后台使用 pthread,因此您也可以使用它。请参阅this discussion 了解更多信息。

我必须做的:

  • 使用较新的 emscripten(我正在使用 1.34.1 进行测试)
  • 安装Firefox Nightly
  • 启用标志 USE_PTHREADS
  • 请注意,这是实验性的,有些东西很挑剔

我在编写一个实际运行的 pthread 示例时遇到了麻烦,但这里的代码使用 std::thread 演示了对我有用的基本功能:

// main.cpp

#include <thread>
#include <iostream>

void func()
{
    std::cout << "I'm a thread!\n";
}

int main()
{
    std::thread test1(func);
    std::thread test2(func);
    std::thread test3(func);

    // join seems to lock up the browser
    //test1.join();
    //test2.join();
    //test3.join();
}

我已经能够在一个更大的项目中使用线程(这里的帖子太大了!),所以它们是可行的。恐怕它们并没有那么快,尽管这可能会随着时间的推移而改善。

构建它:

emcc main.cpp -o main.html -s USE_PTHREADS=1 --std=c++11

Firefox Nightly 42.0a1 (2015-07-16) 中的输出:

为 pthread 生成池预分配 1 个工作线程。
为 pthread 生成池预分配 1 个工作线程。
为 pthread 生成池预分配 1 个工作线程。
我是一个线程!
我是一个线程!
我是一根线!

【讨论】:

  • 我可能稍后会修改我的答案,但this issue 有工作的 pthread 代码,并且正在跟踪 Firefox Nightly 中的冻结情况。
【解决方案2】:

很遗憾,Emscripten 无法编译多线程代码。 Web Worker 允许同时计算,但它们不能保持共享状态,因此不能替代线程。

见: http://kripken.github.io/emscripten-site/docs/porting/guidelines/portability_guidelines.html

编辑:正如其他人指出的那样,Emscripten 自从我最初的回答以来正在向前发展,现在对 pthreads 有实验性支持(可能很快就会支持 C++ 内置线程)https://groups.google.com/forum/#!topic/emscripten-discuss/gQQRjajQ6iY

猜你喜欢
  • 1970-01-01
  • 2022-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多