线程在成功pthread_create之后不执行任何操作

Thread does nothing after successful pthread_create

本文关键字:执行 任何 操作 之后 create 成功 pthread 线程      更新时间:2023-10-16

在我的项目中,我想创建一个线程,它什么都不做,只是在文本文件中附加一些字符串来测试它是否有效。我在Ubuntu 12.04上使用IDE Eclipse Juno。我的部分代码是:

pthread_t processThread;
threadData * thData = new threadData;
int t = pthread_create(&processThread, NULL, 
BufferedData::processData, (void *)thData);

其中,threadData是带线程参数的结构。线程启动BufferedData类的成员函数,因此processData方法是静态的。其声明为:

static void * processData(void * arg);

在这部分代码之后,我检查t值——pthread_create的返回值。每次它都等于0,所以我想线程的启动是成功的。但它仍然什么也不做——它并没有将字符串附加到文件中。processData做什么并不重要:将字符串附加到文件、抛出异常、写入cout或其他什么。它每次都不起作用。

我不是经验丰富的C++程序员,所以我不知道该检查、编辑或做什么来解决问题。IDE没有给我任何错误的回应,它看起来一切都很好。

谢谢你的回答。

编辑:processData函数的代码:

void * BufferedData::processData(void * arg) {
HelperFunctions h;
h.appendToFile("log", "test");
return 0;
}

appendToFile方法将字符串"test"写入文件"log"。这在其他项目中进行了测试,并且行之有效。

现在你的线程将在一段时间内完成(不是无限的),所以这可以帮助你:

int pthread_join(pthread_t thread, void **status);

在下面的code中,当你的线程创建了pthread_join函数,等待你的线程返回。在该状态下使用CCD_ 3而不是CCD_。

试试这个pthread_join():

void *ret;
pthread_t processThread;
threadData * thData = new threadData;
int t = pthread_create(&processThread, NULL, 
BufferedData::processData, (void *)thData);
if (pthread_join(processThread, &ret) != 0) {
perror("pthread_create() error");
exit(3);
}
delete ret;      // dont forget to delete ret (avoiding of memory leak)

pthread_exit():的使用

void * BufferedData::processData(void * arg) {
int *r = new int(10);
HelperFunctions h;
h.appendToFile("log", "test");
pthread_exit(static_cast<void*>(a));
}

概述

允许主叫thread等待目标thread的结束。

pthread_t是用于唯一标识线程的数据类型。它由pthread_create()返回,并由应用程序在需要线程标识符的函数调用中使用。

status包含一个指针,指向作为pthread_exit()的一部分由结束线程传递的状态参数。如果结束线程以返回终止,则状态包含指向return值的指针。如果线程被取消,则状态可以设置为-1

返回值

如果成功,则pthread_join()返回0。如果不成功,pthread_join()返回-1并将errno设置为以下值之一:

错误Code:

Description :
EDEADLK
A deadlock has been detected. This can occur if the target is directly or indirectly joined to the current thread.
EINVAL
The value specified by thread is not valid.
ESRCH
The value specified by thread does not refer to an undetached thread.

注:

pthread_join()成功返回时,表示目标线程已分离。多个线程不能使用pthread_join()来等待同一目标线程结束。如果一个线程在另一个线程成功地为同一目标线程发出pthread_join()之后为该目标线程发出了pthread_join(),则第二个pthread_join()将不成功。

如果调用pthread_join()的线程被取消,则不分离目标线程