我瞭解多線程程序和我期待下面的代碼片斷是打印的無限循環「foo"
,而不是什麼都不會發生在pthread_create不正確執行
期望:
foofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoofoo
實況:
就好像甚至沒有被創建的線程,我在做什麼錯???如何創建一個線程將執行任何功能被分配給它
源代碼
#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的返回值,不檢查它的壞習慣 – Tebe
我猜你的線程不會刷新它們的輸出......但即便如此,你只會得到FooFooFoo,即每個線程有一個Foo – djf