2016-08-13 124 views
2

我有一个C程序,它使用PCRE正则表达式来确定cgroup中的进程是否应该添加到一个变量或另一个变量中。我生成一个线程来读取每个正在运行的cgroup中的cpuacct.stat文件,其中线程数量从未超过核心数量。这些样本和结果然后被组合成两个变量之一。PCRE pcre_exec线程安全吗?

的代码中的相关片段是:

pcreExecRet = pcre_exec(reCompiled, 
         pcreExtra, 
         queue, 
         strlen(queue),   // length of string 
         0,      // Start looking at this point 
         0,      // OPTIONS 
         subStrVec, 
         30);     // Length of subStrVec 

    //CRITICAL SECTION? 
    pthread_mutex_lock(&t_lock); //lock mutex 
    while (sumFlag == 0) { 
     pthread_cond_wait(&ok_add, &t_lock); //wait on ok signal 
    } 

    if(pcreExecRet > 0) { 
     sumOne += loadavg; 
    } else if (pcreExecRet == PCRE_ERROR_NOMATCH){ 
     sumTwo += loadavg; 
    } else { 
     perror("Could not determine sum!\n"); //if this fails 

    } 

    sumFlag = 1; 

    pthread_cond_signal(&ok_add); //signal that it is ok to add 
    pthread_mutex_unlock(&t_lock); //unlock mutex 

我的问题是pcre_exec()调用是否是线程安全的?它是否应该转移到关键部分?我知道编译正则表达式是线程安全的,但我不确定pcreExtra(const pcre_extra)或subStrVec(int * ovector)。目前这些变量是全球性的。

+0

是什么文件为'pcre_exec()'说?此外,您可以使用[* helgrind *](http://www.valgrind.org/info/tools.html#helgrind)检查与线程相关的问题。 –

+0

因为我认为显而易见的原因,Ovector不可共享线程。我会为每个线程分配一个。 – rici

回答

3

是的,它是线程安全的,所有PCRE功能,但你应该在一定条件下

要小心下面是从manual pages for PCRE

MULTITHREADING 

    The PCRE functions can be used in multi-threading applications, with 
    the proviso that the memory management functions pointed to by 
    pcre_malloc, pcre_free, pcre_stack_malloc, and pcre_stack_free, and the 
    callout and stack-checking functions pointed to by pcre_callout and 
    pcre_stack_guard, are shared by all threads. 

    The compiled form of a regular expression is not altered during match- 
    ing, so the same compiled pattern can safely be used by several threads 
    at once. 

    If the just-in-time optimization feature is being used, it needs sepa- 
    rate memory stack areas for each thread. See the pcrejit documentation 
    for more details. 
+0

对,我读过这个,编译后的正则表达式是线程安全的,但我不确定pcre_extra或ovector参数是否可以共享。我也会给helgrind一个尝试。谢谢! – anthozep

+1

@anthozep对于pcre_extra(它实际上是正则表达式定义的一部分)是安全的,但ovector绝对不安全,因为它包含实际匹配* result *。 –

+1

@LucasTrzesniewski对,所有的全局变量当然是不安全的,没有同步。 –