Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python全局变量未更新它';线程中的s值_Python_Multithreading - Fatal编程技术网

Python全局变量未更新它';线程中的s值

Python全局变量未更新它';线程中的s值,python,multithreading,Python,Multithreading,因此,我猜测了python中游戏类型的数量,并且我制作了一个线程服务器来同时接受多个客户端。我想做的一件事是处理我从服务器发送到客户端的每个答案(S-小、H-高、W-赢、L-输),同时发送一条消息,告诉客户端当前连接了多少个客户端,因此client\u count。问题是第一个客户总是被告知有1个客户在玩,第二个客户会被告知有2个玩家,以此类推。全局变量client\u count似乎没有在所有线程上更新 server.py __author__ = 'emil' import socket

因此,我猜测了python中游戏类型的数量,并且我制作了一个线程服务器来同时接受多个客户端。我想做的一件事是处理我从服务器发送到客户端的每个答案(S-小、H-高、W-赢、L-输),同时发送一条消息,告诉客户端当前连接了多少个客户端,因此
client\u count
。问题是第一个客户总是被告知有1个客户在玩,第二个客户会被告知有2个玩家,以此类推。全局变量
client\u count
似乎没有在所有线程上更新

server.py

__author__ = 'emil'

import socket
import threading
import random
import struct
import time

random.seed()
start = 1
stop = 2 ** 17 - 1
my_num = random.randint(start, stop)
print('Server number: ', my_num)
mylock = threading.Lock()
client_guessed = False
winner_thread = 0
e = threading.Event()
e.clear()
threads = []
client_count = 0


def worker(cs):
    global mylock, client_guessed, my_num, winner_thread, client_count, e

    my_idcount = client_count
    print('client #', client_count, 'from: ', cs.getpeername())
    message = 'Hello client #' + \
              str(client_count) + \
              ' ! You are entering the number guess competion now !\n' + \
              'There are currently ' + str(len(threads)) + \
              ' players int game.'
    cs.sendall(bytes(message, 'ascii'))

    players_count_message = "There are currently " + str(client_count) + \
                            " players in game."

    while not client_guessed:
        try:
            cnumber = cs.recv(4)

            if client_guessed:
                break

            cnumber = struct.unpack('!I', cnumber)[0]
            if cnumber > my_num:
                cs.sendall(b'S')
                cs.sendall(bytes(players_count_message, 'ascii'))
            if cnumber < my_num:
                cs.sendall(b'H')
                cs.sendall(bytes(players_count_message, 'ascii'))
            if cnumber == my_num:
                mylock.acquire()
                client_guessed = True
                winner_thread = threading.get_ident()
                mylock.release()

        except socket.error as msg:
            print('Error:', msg.strerror)
            break

    if client_guessed:
        if threading.get_ident() == winner_thread:
            cs.sendall(b'G')
            cs.sendall(bytes(players_count_message, 'ascii'))
            print('We have a winner', cs.getpeername())
            print("Thread ", my_idcount, " winner")
            e.set()
        else:
            cs.sendall(b'L')
            cs.sendall(bytes(players_count_message, 'ascii'))
            print("Thread ", my_idcount, " looser")
    time.sleep(1)
    cs.close()
    print("Worker Thread ", my_idcount, " end")


def reset_srv():
    global mylock, client_guessed, winner_thread, my_num, threads, e, client_count
    while True:
        e.wait()
        for thread in threads:
            thread.join()
        print("all threads are finished now")
        e.clear()
        mylock.acquire()
        threads = []
        client_guessed = False
        winner_thread = 0
        client_count = 0
        my_num = random.randint(start, stop)
        print('Server number: ', my_num)
        mylock.release()


if __name__ == '__main__':
    try:
        rs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        rs.bind(('0.0.0.0', 1234))
        rs.listen(5)
    except socket.error as msg:
        print(msg.strerror)
        exit(-1)

    t = threading.Thread(target=reset_srv, daemon=True)
    t.start()

    while True:
        client_socket, addrc = rs.accept()
        t = threading.Thread(target=worker, args=(client_socket,))
        threads.append(t)
        client_count += 1
        t.start()

你第一次创建玩家计数信息,然后一次又一次地发送!将服务器代码更改为:

def worker(cs):
    .
    .
    .
    players_count_message = "There are currently %s players in game."

    while not client_guessed:
        try:
            .
            .
            .
            if cnumber > my_num:
                cs.sendall(b'S')
                cs.sendall(bytes(players_count_message %(str(client_count)), 'ascii'))
            if cnumber < my_num:
                cs.sendall(b'H')
                cs.sendall(bytes(players_count_message %(str(client_count)), 'ascii'))

            .
            .
            .
def工作者(cs):
.
.
.
players\u count\u message=“游戏中当前有%s名玩家。”
虽然你没有猜到:
尝试:
.
.
.
如果cnumber>my_num:
cs.sendall(b'S')
sendall(字节(玩家计数信息%(客户端计数)),'ascii'))
如果cnumber

此外,您必须检查玩家是否离开游戏或连接关闭,您必须对该变量进行折扣。

是否有可能浓缩为说明问题的消息?您首先创建
players\u count\u消息
,然后一次又一次发送它!
def worker(cs):
    .
    .
    .
    players_count_message = "There are currently %s players in game."

    while not client_guessed:
        try:
            .
            .
            .
            if cnumber > my_num:
                cs.sendall(b'S')
                cs.sendall(bytes(players_count_message %(str(client_count)), 'ascii'))
            if cnumber < my_num:
                cs.sendall(b'H')
                cs.sendall(bytes(players_count_message %(str(client_count)), 'ascii'))

            .
            .
            .