设置线程的优先级 [英] setting priority of threads

查看:84
本文介绍了设置线程的优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好



我正在使用MFC程序接收UDP数据并将其解析为图像。



还有三个额外的线程(在主线程旁边):



1.使用ReceiveFrom()接收UDP数据并将数据保存到缓冲区



2.读取缓冲区并通过fprintf将其写入文本文件()



3.读取缓冲区和解析/写入它通过fwrite()进入图像文件。





有时候(包括其他进程开始运行时)数据丢失文本文件和图像文件,



所以我认为它在ReceiveFrom()中是亏损的。



为了解决这个问题,我想为线程1设置更高的优先级。



现在,没有设置优先级。我只使用CreateThread()。





在推荐文献中,我发现PROCESS_MODE_BACKGROUNG_END是SetPriorityClass()中的一个参数。 />
(和SetThreadPriority()中的THREAD_MODE_BACKGROUND_BEGIN)



我认为这可能很重要,因为我的项目都是关于I / O.



但我不知道参数甚至优先级设置的影响。



我想了解如何它是有效的。



你能告诉我有关优先级设置以及你是否认为可以解决问题的方法吗?







-----已添加-----



全局变量:



  #define SIZE_BUFFER 50 
#define SIZE_PACKET 414
static char buffer_received [SIZE_BUFFER] [SIZE_PACKET] ;
static 无符号 int ,out_log,out_image;







线程1正在运行:



  char 收到[SIZE_PACKET]; 
while 1
{
// 阻止直到从客户端接收消息
int recvMsgSize = udpServer.ReceiveFrom(已收到,SIZE_PACKET,senderIP,senderPort);

mu。 lock ();
if in + 1 < SIZE_BUFFER)
memcpy_s(buffer_received [ in + 1 ],SIZE_PACKET,收到,SIZE_PACKET);
else
memcpy_s(buffer_received [ 0 ],SIZE_PACKET,已收到,SIZE_PACKET) ;
in ++;
if in == SIZE_BUFFER)
in = 0 ;
mu.unlock();

}







线程2正在运行:



  while  1 
{
if in != out_log)
{
out_log ++;
if (out_log == SIZE_BUFFER)
out_log = 0 ;

memcpy_s(buffer,SIZE_PACKET,buffer_received [out_log],SIZE_PACKET);

stringToHexa_WiresharkForm(buffer,SIZE_PACKET,buffer_hex);

Decode_NavData(buffer);
fprintf(ptr_logFile, %s\\\
\ n
,buffer_hex);
count ++;

if (count > 5000
{
fflush(ptr_logFile);
count = 0 ;
}


}

}





线程3正在运行:



  while  1 
{
if in != out_image)
{
out_image ++;
if (out_image == SIZE_BUFFER)
out_image = 0 ;

memcpy_s(buffer,SIZE_PACKET,buffer_received [out_image],SIZE_PACKET);

if (!Decode_Image(buffer))
return < span class =code-digit> 0 ;
}
}







上面的代码是每个代码的核心部分线。 (删除了不必要的代码)



我认为重要的事情是变量'in'和写入'buffer_received'的增量时间。但是我认为时机得到了很好的处理。



有时候,在读取(线程1)和写入(线程2,3)例程中,有数据丢失。



UDP数据以414字节(称为数据包)的形式从其他设备发送,每秒400个数据包。



如果同步和优先级都不是问题,我认为这是代码的设计。



1.读取缓冲区大小ReceiveFrom()?



2. while循环设计?



我怀疑超过两个,但是没有解决方案。

解决方案

根据你的解释,我认为没有必要改变任何优先事项。



线程的影响(并且,不要忘记,也是影响进程线程的组合优先级的进程优先级)在Windows中它完全是概率性的。与此同时,长时间将优先级提升到极端,将阻止其他线程,甚至是驱动程序操作。在绝大多数情况下,不接触优先级是最佳策略。



更改或优先级可用于微调概率,略微提高总体性能(但什么可以保证它不仅可以帮助 ad-hoc ?),而且这种情况非常罕见。此外,例如,对于硬件,您可以将时间关键优先级用于代码任务关键代码的短片段,但严格来说,并不是真的要保证这个片段能够及时执行,而是降低概率与错误时序相关的故障,事实上,它主要用于弥补硬件的一些设计缺陷,这可能太过于原始而无法保证实时性。



我希望您了解优先级不能也不应该用于影响操作顺序。如果操作顺序取决于时间,这是不正确的,通常是灾难的根源: http://en.wikipedia.org/ wiki / Race_condition [ ^ ]。



更准确地说,这不是优先考虑的问题,而只是错误的线程设计的指示。也就是说,人们有一些错误的设计,首先受到比赛条件的影响,然后有些人试图改变优先级以改变比赛状态,以期达到预期的操作顺序。最危险的情况是他们成功地观察到了预期的效果;系统可以在不确定的时间段内正常工作,并在生产过程中崩溃一段时间。 :-)我希望你没有计划这种虐待。



-SA


< blockquote> UDP读取对于获取输入非常重要,因此我会使用普通优先级。我更喜欢对非前台线程使用THREAD_PRIORITY_BELOW_NORMAL标志。如果你去低,他们不会跑,但等待。没有理由去低,你最好在现实条件下测试它。看起来工作量太大了。



微软对线程优先级有自己的想法。阅读并理解它。


Hello

I'm working with MFC program which receives UDP data and parses it to images.

There are three additional threads (beside main thread):

1. receiving UDP data by using ReceiveFrom() and saving the data into buffer

2. reading buffer and writing it to text file by fprintf()

3. reading buffer and parsing/writing it into image file by fwrite().


Sometimes (including when other processes start to run) there is some data loss both in text file and image file,

so I think it was a loss in ReceiveFrom().

In order to resolve the problem, I would like to set higher priority to thread 1.

Now, there is no priority set. I'm using just CreateThread().


In referring literature, I found PROCESS_MODE_BACKGROUNG_END as a parameter in SetPriorityClass().
(and THREAD_MODE_BACKGROUND_BEGIN in SetThreadPriority())

I think it might be important because my project is all about I/O.

But I have no idea about effect of the parameter and even of the priority set.

I want to understand how it works.

Can you advise me regarding priority set and whether you think that can solve the problem?



----- added -----

Global variables:

#define SIZE_BUFFER 50
#define SIZE_PACKET 414
static char buffer_received[SIZE_BUFFER][SIZE_PACKET];
static unsigned int in, out_log, out_image;




Thread 1 is running:

char received[SIZE_PACKET];
while (1)
    {
        // Block until receive message from a client
        int recvMsgSize = udpServer.ReceiveFrom(received, SIZE_PACKET, senderIP, senderPort);

        mu.lock();
        if (in + 1 < SIZE_BUFFER)
            memcpy_s(buffer_received[in + 1], SIZE_PACKET, received, SIZE_PACKET);
        else
            memcpy_s(buffer_received[0], SIZE_PACKET, received, SIZE_PACKET);
        in++;
        if (in == SIZE_BUFFER)
            in = 0;
        mu.unlock();

    }




Thread 2 is running:

while (1)
    {
        if (in != out_log)
        {
            out_log++;
            if (out_log == SIZE_BUFFER)
                out_log = 0;

            memcpy_s(buffer, SIZE_PACKET, buffer_received[out_log], SIZE_PACKET);

            stringToHexa_WiresharkForm(buffer, SIZE_PACKET, buffer_hex);

            Decode_NavData(buffer);
            fprintf(ptr_logFile, "%s\n\n", buffer_hex);
            count++;

            if (count > 5000)
            {
                fflush(ptr_logFile);
                count = 0;
            }


        }

    }



Thread 3 is running:

while (1)
    {
        if (in != out_image)
        {
            out_image++;
            if (out_image == SIZE_BUFFER)
                out_image = 0;

            memcpy_s(buffer, SIZE_PACKET, buffer_received[out_image], SIZE_PACKET);

            if (!Decode_Image(buffer))
                return 0;
        }
    }




The code above is the core part of each thread. (unnecessary codes were removed)

I think the important things are timing of increment of variable 'in' and writing to 'buffer_received'. But the timing is well treated I think.

Sometimes, in one of reading (thread 1) and writing (thread 2, 3) routine, there is data loss.

The UDP data is being sent from other device in a bunch of 414 bytes (called packet), and 400 packets per second.

If neither of synchronization and priority is the problem, I think it is the design of the code.

1. read buffer size in ReceiveFrom() ?

2. while loop design ?

I'm doubting above two, but have no solution.

解决方案

From your explanation, I see no need in changing any priorities.

The effect of thread (and, don't forget, also the process priority which affects combined priority of the process's thread) in Windows it totally probabilistic. At the same time, boosting the priority to the extremes, for a prolonged period of time, will block other threads, even the driver operation. In absolute majority of cases, not touching priorities is the best strategy.

Changing or priorities can be use for fine tuning of the probabilities, to slightly increase total performance (but what can guarantees it can help not only ad-hoc?), and such situations are very rare. Also, for example, with hardware, you can use time-critical priority for a short fragment of code mission-critical code, but, strictly speaking, not really to guarantee that this fragment will be executed in time, but rather to reduce the probability of failures related to bad timing, and, in fact, it's mostly done to compensate some design defect of hardware, which could be just too primitive to guarantee real-time under the hood.

I hope you understand that priorities cannot be and shouldn't be used to affect the order of operation. If the order of operation depends on timing, this is incorrect and is generally a source of disasters: http://en.wikipedia.org/wiki/Race_condition[^].

More exactly, this is the problem not of priorities, but only the indication of wrong threading design. That is, people have some wrong design which suffers from racing condition in first place, and then some try to change the priorities to shift the racing condition in hope to achieve desired order of operations. The most dangerous situation is when they succeed in observing the desired effect; the the system can work seemingly correctly for undefined period of time and crash some time during production. :-) I hope you haven't been planning such kind of abuse.

—SA


The UDP reading is important for getting input and NOT missing it, so I would use normal priority. I prefer using the THREAD_PRIORITY_BELOW_NORMAL flag for non-foreground threads. If you go to low, they wont run but wait. There is no reason for going to low and you better test it under realistic conditions. Its looks like the workload isnt too heavy.

Microsoft has its own ideas about Thread priority. Read and understand it.


这篇关于设置线程的优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆