繁体   English   中英

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

[英]Thread does nothing after successful pthread_create

在我的项目中,我想创建线程,该线程除了将一些字符串附加到文本文件以测试其是否起作用外什么也不做。 我在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时,我就认为线程的开始是成功的。 但它仍然无能为力-它不会将字符串附加到文件中。 进程data的功能无关紧要:将字符串追加到文件,引发异常,写入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函数将等待线程返回。 在这种状态下,请使用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值终止,则状态包含指向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()的线程,则不会分离目标线程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM