A few lines of Python that will make stuff easier.

Jun 12, 2009 22:31

This piece of code (written in Python) has probably been written many times, by many people, but then again, it's useful.

import os

def myfork(thing):
"""myfork(thing) executes thing() in a separate thread"""

pid = os.fork()

if not pid:
#We're in the child thread now.
thing()
exit()
else:
#Parent thread.
return pid
As a simple example, here is a little program that will ask the user for a number, and print "Hello, world!" that often. However, it also prints a series of dashes every second. We use two threads, one that asks for input and prints "Hello, world!", and one that prints the dashes. The code snippet above is assumed to live in the module "myfork".

from myfork import *
import time

def askThread():
num = input("A number!")
print ("Hello, world!\n" * num),

myfork(askThread)

while(1):
print "------"
time.sleep(1)
So, yes. I'm not sure how safe it is with exceptions and such, but it works. And it looks better than having if-statements all over the place.
Previous post Next post
Up