如何使用多个线程

时间:2012-03-02 11:06:20

标签: python multithreading

我有这段代码:

import thread

def print_out(m1, m2):
    print m1
    print m2
    print "\n"

for num in range(0, 10):
    thread.start_new_thread(print_out, ('a', 'b'))

我想创建10个线程,每个线程运行函数print_out,但我失败了。错误如下:

Unhandled exception in thread started by 
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by 
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by 
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by 
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by 
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by 
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by 
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by 
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by 
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by 
sys.excepthook is missing
lost sys.stderr

5 个答案:

答案 0 :(得分:13)

首先,您应该使用更高级别的threading模块,特别是Thread类。 thread模块不是您所需要的。

在扩展此代码时,您很可能也希望等待线程完成。以下是如何使用join方法实现该目标的演示:

import threading

class print_out(threading.Thread):

    def __init__ (self, m1, m2):
        threading.Thread.__init__(self)
        self.m1 = m1
        self.m2 = m2

    def run(self):
        print self.m1
        print self.m2
        print "\n"

threads = []
for num in range(0, 10):
    thread = print_out('a', 'b')
    thread.start()
    threads.append(thread)

for thread in threads:
    thread.join()

答案 1 :(得分:2)

你应该让主线保持活力一段时间。如果主线程死掉,所有其他线程也会死掉,因此您将看不到任何输出。尝试在代码末尾添加time.sleep(0.1),然后您将看到输出。

之后,您可以查看thread.join()以了解更多信息。

答案 2 :(得分:2)

另一种方法是使用线程类。

 instance[num]=threading.Thread(target=print_out, args=('a', 'b'))

 instance[num].start()

答案 3 :(得分:0)

使用线程模块,您需要通过在下面添加while循环来运行主线程

import thread

def print_out(m1, m2):
    print m1
    print m2
    print "\n"

for num in range(0, 10):
    thread.start_new_thread(print_out, ('a', 'b'))`

while(1):
    pass

答案 4 :(得分:0)

无论何时创建线程,都需要在此之前运行主线程。 在这里,您没有运行任何主踏板。

要解决此问题,您可以添加任何其他语句的打印语句。 让我们修改您的代码

const intialState = {
    output: [],
    bookIdToDelete: null
  }
  const [state,setState] = useState(intialState)

  useEffect(() => {
    getDataFromServer().then(data => {
      console.log(data);
      if (data != 2) {
        // job gonna be here
        const output = data
        setState({...state, output})
      }
    }).catch(error => {
      console.log(error);
    })
  }, [])


  const deleteBtnClick = (e) => {
    let bookId = e.target.id;
    console.log(state)
    setState({
        ...state,
        bookIdToDelete: bookId
     })
  }          
  return (
    <>

       {state.output.map(book => {
          return (
            <div key={book._id} className="col-md-3">
              <div className="item">
                <img className="bookimage" src={book.imgs[0]} alt="img"/>
                <h3>
                  <Link to={"/admin/mybook/" + book._id}>{book.title}</Link>
                </h3>
                <h6>
                  <Link to={"/admin/mybook/" + book._id}>Edit</Link>&nbsp;&nbsp;&nbsp;
                  <button id={book._id} onClick={deleteBtnClick} className="btn btn-    danger">Delete</button>
                </h6>
              </div>
            </div>
          )
        })}

    </>
  )
}

export default MyBooks  

在这里time.sleep()为您创建主踩,而thread.start_new_thread在主踩上创建10个线程。 注意:您可以添加任何语句代替time.sleep()

相关问题