Python中的多线程问题

时间:2016-03-13 00:46:58

标签: python multithreading

新的Python多线程并编写这样简单的程序,这里是我的代码和错误信息,任何想法有什么不对?感谢。

使用Python 2.7。

import time
import thread

def uploader(threadName):

    while True:
        time.sleep(5)
        print threadName

if __name__ == "__main__":

    numOfThreads = 5
    try:
        i = 0
        while i < numOfThreads:
            thread.start_new_thread(uploader, ('thread'+str(i)))
            i += 1

        print 'press any key to exit test'
        n=raw_input()

    except:
       print "Error: unable to start thread"

Unhandled exception in thread started by <pydev_monkey._NewThreadStartupWithTrace instance at 0x10e12c830>
Traceback (most recent call last):
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydev_monkey.py", line 521, in __call__
    return self.original_func(*self.args, **self.kwargs)
TypeError: uploader() takes exactly 1 argument (7 given)
提前谢谢, 林

2 个答案:

答案 0 :(得分:3)

('thread' + str(i)) # results in a string need to be a tuple的算论。而不是:

('thread' + str(i),)  # a tuple with a single element

尝试使用args:

thread

顺便说一句,您应该查看threading module,这是一个比package main.main.start; import javax.swing.JTextField; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.io.File; import java.io.IOException; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import javax.imageio.ImageIO; import javax.swing.JFrame; import main.main.start.graphics.Screen; public class start extends Canvas implements Runnable{ private static final long serialVersionUID = 1L; public static int width = 320; public static int height = width / 16 * 9; public static int scale = 3; public boolean up,left,right,down; public BufferedImage keine,floor,wall,test; public int xaxis,yaxis;{ xaxis = 50; yaxis = 50; } private Thread thread; private JFrame frame; private BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB ); private int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData(); private boolean running = false; private Screen screen; public start (){ Dimension size = new Dimension(width*scale,height*scale); setPreferredSize (size); screen = new Screen(width, height); frame = new JFrame(); } public synchronized void start() { running = true; thread = new Thread(this, "Display"); thread.start(); } public synchronized void stop(){ running = false; try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public void run(){ while(running == true){ //rendering&updating //System.out.println("running..."); update(); render(); } } public void update() { } public void render() { BufferStrategy bs = getBufferStrategy(); if(bs == null){ createBufferStrategy(3); return; } screen.clear(); screen.render(); for(int i = 0; i < pixels.length; i++){ pixels[i] = screen.pixels[i]; } Graphics g = bs.getDrawGraphics(); g.setColor(Color.BLUE); g.fillRect(0,0,getWidth(), getHeight() ); g.drawImage(image, 0, 0, getWidth(),getHeight(),null); //playercontrollerstart //playercontrollerend //map int[][] map= { {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}, {10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10} }; int rows = 20; int cols = 20; int i, j; try { keine = ImageIO.read(new File("keine.png")); floor = ImageIO.read(new File("floor.png")); wall = ImageIO.read(new File("wall.png")); test = ImageIO.read(new File("test.png")); } catch (IOException e) { e.printStackTrace(); } for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { if(map[i][j] == 10){ g.drawImage(keine,i*32,j*32,this); } if(map[i][j] == 11){ g.drawImage(wall,i*32,j*32,this); } if(map[i][j] == 12){ g.drawImage(floor,i*32,j*32,this); } } g.drawImage(test,xaxis,yaxis,this); } //mapend g.dispose(); bs.show(); } public static void main(String[] args) { start game = new start(); game.frame.setResizable(false); game.frame.setTitle("TestWindowName"); game.frame.add(game); game.frame.pack(); game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); game.frame.setLocationRelativeTo(null); game.frame.setVisible(true); game.start(); } 更高级别的界面。

答案 1 :(得分:1)

在下文中,threadName现在是一个在程序代码顶部定义的全局变量,然后在新线程启动之前初始化变量,目标是上传函数。

试试这个:

import time
import thread

threadName = ''

def uploader():

    while True:
        time.sleep(5)
        print threadName

if __name__ == "__main__":

    numOfThreads = 5
    try:
        i = 0
        while i < numOfThreads:
            threadName = 'thread' + str(i)
            newThread = threading.Thread(target=uploader)
            newThread.start()
            i += 1

        print 'press any key to exit test'
        n=raw_input()

    except:
       print "Error: unable to start thread"