PThread - 尽管调用pthread_join,线程仍然提前退出

时间:2015-03-23 10:18:35

标签: c++ multithreading pthreads pthread-join

我已经以相当基本的方式实现了PThreads:

#include<iostream>
#include<pthread.h>
#include<stdio.h>

using namespace std;

class ThreadParameter
{
public:
char symbol_char;
int count;
};

void* print_char (void* param)
{

ThreadParameter* p = (ThreadParameter*)param;

for (int i=0; i< p->count; i++)
{
cout<< p->symbol_char <<endl;
i++;
}
return NULL;
}

int main ()
{
pthread_t thread1_id;

ThreadParameter param1;

param1.symbol_char = 'X';
param1.count = 27;

pthread_create (&thread1_id, NULL, &print_char, &param1);

int i = 0;

while (i<10)
{
cout<<"O"<<endl;
i++;
}

pthread_join(thread1_id,NULL);

return 0;
}

它的输出没有显示X的预期值。我在调用join函数时做错了什么?谢谢你的帮助。

Output

P.S:我已经尝试了从5到20的各种X值,但它总是比我想要的X数小。

1 个答案:

答案 0 :(得分:1)

您在i中两次递增print_char()

更改

for (int i=0; i< p->count; i++)
{
    cout<< p->symbol_char <<endl;
    i++;
}

进入

for (int i=0; i< p->count; i++)
{
    cout<< p->symbol_char <<endl;
}