成功的pthread_create后,线程不执行任何操作

时间:2012-12-04 09:55:07

标签: c++ pthreads

在我的项目中,我想创建一个除了在文本文件中追加一些字符串以测试它是否有效的线程。我在Ubuntu 12.04上使用IDE Eclipse Juno。我的部分代码是:

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

其中threadData是带有线程参数的struct。类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”。这在其他项目中进行了测试,并且有效。

1 个答案:

答案 0 :(得分:1)

现在您的线程将在一段时间内完成(不是无限的),因此可以为您提供帮助:

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

在下面的code中,当您的线程创建时,pthread_join函数将等待线程返回。在这种状态下,使用pthread_exit()而不是return关键字。

尝试以下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()的线程被取消,则目标线程不会被分离

相关问题