简体   繁体   English

在多线程中附加字符串

[英]Appending string in multi-threading

I'm doing multi-threading and trying to append ' ,F ' into the msg (string) ' pSDATA,0,4,2,2,0,4\\n '.我正在执行多线程并尝试将 ' ,F ' 附加到 msg(字符串)' pSDATA,0,4,2,2,0,4\\n ' 中。 Ultimately I would like to get ' pSDATA,0,4,2,2,0,4,F\\n ' However when I run the following code:最终我想得到 ' pSDATA,0,4,2,2,0,4,F\\n ' 但是当我运行以下代码时:

if(msg[0].lower() == 'p'):
    msg = msg[:-1] + ',F\n'
    pcQueue.put_nowait(msg[1:])
    print ("Message received: ") + msg[1:]

I got the following result:我得到了以下结果:

,Fssage received: SDATA,0,4,2,2,0,4

I'm suspecting this is due to multi-threading.我怀疑这是由于多线程。 Any help would be greatly appreciated!任何帮助将不胜感激!

If you were trying to remove a trailing newline with msg[:-1] , be aware that the string could have ended with "\\r\\n" .如果您尝试使用msg[:-1]删除尾随换行符,请注意该字符串可能以"\\r\\n"结尾。 \\r commonly has the effect of going back to the beginning of the line of output and continuing to write there. \\r通常具有返回到输出行开头并继续在那里写入的效果。 The right course of action depends on exactly why you wanted to remove the trailing newline, but if you wanted to remove exactly one from the end, optionally, supporting both \\r\\n and \\n , here's how you could do it:正确的行动方案取决于您想要删除尾随换行符的确切原因,但如果您想从末尾删除一个,可选地,同时支持\\r\\n\\n ,您可以这样做:

def chomp(s):
    if s.endswith('\n'):
        if s.endswith('\r\n'):
            return s[:-2]
        return s[:-1]
    return s

⋮

if msg[0].lower() == 'p':
    msg = chomp(msg) + ',F\n'
    ⋮

Other things to choose from might include msg.rstrip() to remove any amount of all whitespace from the end, msg[:-2] if you know for sure it always ends with CR LF, ….其他可供选择的内容可能包括msg.rstrip()从末尾删除任意数量的所有空格, msg[:-2]如果您确定它总是以 CR LF 结尾,...。

Also, if whatever protocol involved specifies a preference for CR LF, or even if it's just consistent with what you're passing along, you might want to be adding ,F\\r\\n instead of ,F\\n .此外,如果所涉及的任何协议指定了对 CR LF 的偏好,或者即使它与您传递的内容一致,您可能希望添加,F\\r\\n而不是,F\\n

If you have multiple threads that print to the console at the same time, the printing isn't guaranteed to be atomic.如果您有多个线程同时打印到控制台,则不能保证打印是原子的。 This means that messages from different threads could indeed get interleaved on the console.这意味着来自不同线程的消息确实可以在控制台上交错。 If that's a problem, you should use synchronisation ( http://effbot.org/zone/thread-synchronization.htm ).如果这是一个问题,您应该使用同步( http://effbot.org/zone/thread-synchronization.htm )。

On the other hand, there's no reason to think that the messages getting put on the queue are corrupt in any way.另一方面,没有理由认为放入队列的消息以任何方式损坏。 If you think otherwise, you'll need to provide more details.如果您不这么认为,则需要提供更多详细信息。

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

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