【发布时间】:2014-02-19 08:14:20
【问题描述】:
我正在学习多线程程序,并希望下面的 sn-p 代码是打印“foo"”的无限循环,而不是什么都没有发生
期望:
foofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoo
现实:
好像连线程都没有创建,我做错了什么???我如何创建一个线程来执行分配给它的任何功能
源代码
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
void* print(void*);
struct threadInfo
{
int threadID;
int threadNo;
};
int main()
{
pthread_t thread[3];
bool cont = false;
int i = 1;
int max = 3;
while ( cont == false )
{
if ( i <= max )
{
threadInfo t_info;
t_info.threadID = i ;
t_info.threadNo = i ;
pthread_create(&thread[i-1],NULL,print,(void*)&t_info);
i++;
}
}
}
void* print(void* arg)
{
std::cout << "Foo" ;
pthread_exit(NULL);
}
以下代码是在 Ubuntu 命令行上使用以下命令编译的
g++ test.cpp -o test -lpthread
【问题讨论】:
-
检查phread_create的返回值,不检查是坏习惯
-
我猜你的线程没有刷新它们的输出......但即便如此,你也只会得到 FooFooFoo,即每个线程一个 Foo
标签: c++ c multithreading debugging posix