c++ - PThread - 尽管调用了 pthread_join,但线程提前退出

标签 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 数。

最佳答案

您在 print_char() 中递增了 i 两次。

改变

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;
}

关于c++ - PThread - 尽管调用了 pthread_join,但线程提前退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29207732/

相关文章:

c++ - 用许多 block 实现的 vector ,没有调整大小的拷贝

java - Java中的生产者/消费者 : keeping it balanced

multithreading - QThread 中的 Worker

java - 线程在 Mule 1.3 中如何工作?

c++ - MPI_Wait 使简单程序崩溃

c++ - Qt 虚拟键盘和 QInputContextFactory

c - 线程同步的障碍

c - 如何从主线程唤醒休眠线程?

c - 难以创建 Pthread(错误 22)

c++ - 使用 fstream 读取带有 float 的 vector