From python-checkins at python.org Fri Mar 2 23:12:55 2007 From: python-checkins at python.org (richard.tew) Date: Fri, 2 Mar 2007 23:12:55 +0100 (CET) Subject: [Stackless-checkins] r54092 - in stackless/sandbox/examples/pyqt: producer-consumer producer-consumer/producer_consumer.py producer-consumer/producer_consumer_ui.py Message-ID: <20070302221255.D48B01E4005@bag.python.org> Author: richard.tew Date: Fri Mar 2 23:12:53 2007 New Revision: 54092 Added: stackless/sandbox/examples/pyqt/ stackless/sandbox/examples/pyqt/producer-consumer/ stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer.py stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer_ui.py Log: Committed Carlos Eduardo de Paula's PyQT example. Added: stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer.py ============================================================================== --- (empty file) +++ stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer.py Fri Mar 2 23:12:53 2007 @@ -0,0 +1,261 @@ +# +# This is a small producer-consumer application integrated with PyQt. +# +# Author: Carlos Eduardo de Paula +# +# The application uses no threads, all is done by tasklets, simple but +# is valid and can be extended. +# +# If you have any questions about this example, please feel free to +# contact the Stackless mailing list. You can subscribe at this +# address: +# +# http://www.tismer.com/mailman/listinfo/stackless +# + +import stackless +import time +import random +import sys +from PyQt4 import QtGui, QtCore + + +# Nice way to put the tasklet to sleep - from stackless.com wiki/Idioms +########################################################## +sleepingTasklets = [] + +def Sleep(secondsToWait): + channel = stackless.channel() + endTime = time.time() + secondsToWait + sleepingTasklets.append((endTime, channel)) + sleepingTasklets.sort() + # Block until we get sent an awakening notification. + channel.receive() + +def ManageSleepingTasklets(): + while 1: + if len(sleepingTasklets): + endTime = sleepingTasklets[0][0] + if endTime <= time.time(): + channel = sleepingTasklets[0][1] + del sleepingTasklets[0] + # We have to send something, but it doesn't matter what as it is not used. + channel.send(None) +# if len(sleepingTasklets) <= 0: time.sleep(endTime-time.time()) + #time.sleep(0.001) + stackless.schedule() + if len(sleepingTasklets) <= 0: stackless.getcurrent().kill() + +#stackless.tasklet(ManageSleepingTasklets)() + +########################################################## + +class Agent(object): + def __init__(self, name=None): + self.ch = stackless.channel() + self.name = name + self.items = 0 + self.kill = False + self.t = stackless.tasklet(self.runAction)() + + def runAction(self): + while not self.kill: + self.action() + + def action(self): + pass + +class Queue(object): + def __init__(self, name): + self.queue_start=0 + self.qt = self.queue_start + self.max_size = 100 + self.running = False + self.kill = False + self.produced = 0 + self.consumed = 0 + self.q_empty = 0 + self.q_full = 0 + self.producers = [] + self.consumers = [] + + def put(self, qty=1, who=None): + if self.qt+qty < self.max_size: + self.qt += qty + self.produced += 1 + else: + self.q_full += 1 + + def get(self, qty=1, who=None): + if self.qt >= qty: + self.qt -= qty + self.consumed += 1 + else: + self.q_empty += 1 + + +class Producer(Agent): + def __init__(self,name, queue): + Agent.__init__(self, name) + self.time = random.random() + self.items = 0 + self.queue = queue + self.queue.producers.append(self) + + def action(self): + while self.queue.running: + if self.queue.qt < 5: + Sleep(self.time) + else: + Sleep(self.time*2) + self.queue.put(1, self.name) + self.items += 1 + else: + Sleep(self.time) + +class Consumer(Agent): + def __init__(self, name, queue): + Agent.__init__(self, name) + self.time = random.random() + self.queue = queue + self.queue.consumers.append(self) + def action(self): + while self.queue.running: + self.queue.get(1, self.name) + self.items += 1 + if self.queue.qt < 5: + Sleep(self.time*2) + else: + Sleep(self.time) + else: + Sleep(self.time) + +########################################################################## + +class mainWindow(QtGui.QMainWindow): + def __init__(self): + QtGui.QMainWindow.__init__(self) + from producer_consumer_ui import Ui_MainWindow + # Set up the user interface from Designer. + self.ui = Ui_MainWindow() + self.ui.setupUi(self) + self.connect(self.ui.start, QtCore.SIGNAL("clicked()"),self.start) # <- Button + self.connect(self.ui.stop, QtCore.SIGNAL("clicked()"),self.stop) # <- Button + self.connect(self.ui.add, QtCore.SIGNAL("clicked()"),self.addtoqueue) # <- Button + self.connect(self.ui.addprod, QtCore.SIGNAL("clicked()"),self.addprod) # <- Button + self.connect(self.ui.addcons, QtCore.SIGNAL("clicked()"),self.addcons) # <- Button + + self.started = False + self.killtasks = False + self.q = Queue("Queue") + self.PID = 0 + self.CID = 0 + + def closeEvent(self, event): + self.killtasks = True + try: + for p in self.q.producers: + p.kill = True + for c in self.q.consumers: + c.kill = True + self.sleepMan.kill() + self.showReport() + except: pass + + def start(self): + if self.started: + self.q.running = True + self.ui.statusbar.showMessage("Running") + return + self.ui.statusbar.showMessage("Starting up...") + self.started = True + self.q.running = True + self.sleepMan = stackless.tasklet(ManageSleepingTasklets)() + self.monit = stackless.tasklet(self.monitor)() + self.ui.queue.setMaximum(self.q.max_size) + + for i in range(num_prod): + self.addprod() + + for i in range(num_cons): + self.addcons() + + self.ui.statusbar.showMessage("Running") + stackless.run() + + + def stop(self): + self.q.running = False + self.ui.statusbar.showMessage("Stopped") + + def addprod(self): + ID = self.PID + name = "P"+str(ID) + a = Producer(name, self.q) + self.PID += 1 + + def addcons(self): + ID = self.CID + name = "C"+str(ID) + a = Consumer(name, self.q) + self.CID += 1 + + def addtoqueue(self): + self.q.qt += 10 + + def monitor(self): + while not self.killtasks: + QtGui.QApplication.processEvents() + self.ui.queue.setValue(self.q.qt) + self.ui.prod.setText(str(len(self.q.producers))) + self.ui.cons.setText(str(len(self.q.consumers))) + Sleep(0.033) + #stackless.schedule() + + def showReport(self): + print + print "--------------------------" + for p in self.q.producers: + print "Producer", p.name , "produced: ", p.items, "items. Each production took: ", p.time + print + for c in self.q.consumers: + print "Consumer", c.name , "consumed: ", c.items, "items. Each consuption took: ", c.time + print "--------------------------" + print "Produced units: ", self.q.produced + print "Consumed units: ", self.q.consumed + print "Left in queue: ", self.q.qt + print + print "Queue became zero ", self.q.q_empty, " times." + print "Queue became full ", self.q.q_full, " times." + print + print "--------------------------" + + + +########################################################### + +num_prod = 10 # Number of starting producers +num_cons = 10 # Number of starting consumers + + +def main(args): + app = QtGui.QApplication(sys.argv) + mainwindow = mainWindow() + mainwindow.show() + sys.exit(app.exec_()) + +if __name__=="__main__": + main(sys.argv) + + + + + + + + + + + + + Added: stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer_ui.py ============================================================================== --- (empty file) +++ stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer_ui.py Fri Mar 2 23:12:53 2007 @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- + +# Used by producer_consumer.py + +# Form implementation generated from reading ui file 'prodcon_ui.ui' +# +# Created: Tue Aug 29 15:41:04 2006 +# by: PyQt4 UI code generator 4-snapshot-20060814 +# +# WARNING! All changes made in this file will be lost! + +import sys +from PyQt4 import QtCore, QtGui + +class Ui_MainWindow(object): + def setupUi(self, MainWindow): + MainWindow.setObjectName("MainWindow") + MainWindow.resize(QtCore.QSize(QtCore.QRect(0,0,392,351).size()).expandedTo(MainWindow.minimumSizeHint())) + + self.centralwidget = QtGui.QWidget(MainWindow) + self.centralwidget.setObjectName("centralwidget") + + self.cons = QtGui.QLineEdit(self.centralwidget) + self.cons.setGeometry(QtCore.QRect(80,170,31,20)) + self.cons.setObjectName("cons") + + self.stop = QtGui.QPushButton(self.centralwidget) + self.stop.setGeometry(QtCore.QRect(60,70,75,23)) + self.stop.setObjectName("stop") + + self.start = QtGui.QPushButton(self.centralwidget) + self.start.setGeometry(QtCore.QRect(60,40,75,23)) + self.start.setObjectName("start") + + self.addprod = QtGui.QPushButton(self.centralwidget) + self.addprod.setGeometry(QtCore.QRect(270,160,75,23)) + self.addprod.setObjectName("addprod") + + self.label = QtGui.QLabel(self.centralwidget) + self.label.setGeometry(QtCore.QRect(20,150,48,14)) + self.label.setObjectName("label") + + self.prod = QtGui.QLineEdit(self.centralwidget) + self.prod.setGeometry(QtCore.QRect(80,150,31,20)) + self.prod.setObjectName("prod") + + self.addcons = QtGui.QPushButton(self.centralwidget) + self.addcons.setGeometry(QtCore.QRect(270,130,75,23)) + self.addcons.setObjectName("addcons") + + self.label_2 = QtGui.QLabel(self.centralwidget) + self.label_2.setGeometry(QtCore.QRect(20,171,53,14)) + self.label_2.setObjectName("label_2") + + self.add = QtGui.QPushButton(self.centralwidget) + self.add.setGeometry(QtCore.QRect(270,40,75,23)) + self.add.setObjectName("add") + + self.lcdNumber = QtGui.QLCDNumber(self.centralwidget) + self.lcdNumber.setGeometry(QtCore.QRect(170,40,64,23)) + self.lcdNumber.setObjectName("lcdNumber") + + self.queue = QtGui.QProgressBar(self.centralwidget) + self.queue.setGeometry(QtCore.QRect(190,80,22,211)) + self.queue.setMaximum(60) + self.queue.setProperty("value",QtCore.QVariant(0)) + self.queue.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) + self.queue.setOrientation(QtCore.Qt.Vertical) + self.queue.setInvertedAppearance(False) + self.queue.setTextDirection(QtGui.QProgressBar.TopToBottom) + self.queue.setObjectName("queue") + MainWindow.setCentralWidget(self.centralwidget) + + self.menubar = QtGui.QMenuBar(MainWindow) + self.menubar.setGeometry(QtCore.QRect(0,0,392,21)) + self.menubar.setObjectName("menubar") + MainWindow.setMenuBar(self.menubar) + + self.statusbar = QtGui.QStatusBar(MainWindow) + self.statusbar.setObjectName("statusbar") + MainWindow.setStatusBar(self.statusbar) + + self.retranslateUi(MainWindow) + QtCore.QObject.connect(self.queue,QtCore.SIGNAL("valueChanged(int)"),self.lcdNumber.display) + QtCore.QMetaObject.connectSlotsByName(MainWindow) + + def retranslateUi(self, MainWindow): + MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) + self.stop.setText(QtGui.QApplication.translate("MainWindow", "Stop", None, QtGui.QApplication.UnicodeUTF8)) + self.start.setText(QtGui.QApplication.translate("MainWindow", "Start", None, QtGui.QApplication.UnicodeUTF8)) + self.addprod.setText(QtGui.QApplication.translate("MainWindow", "+ Prod", None, QtGui.QApplication.UnicodeUTF8)) + self.label.setText(QtGui.QApplication.translate("MainWindow", "Producers", None, QtGui.QApplication.UnicodeUTF8)) + self.addcons.setText(QtGui.QApplication.translate("MainWindow", "+ Cons", None, QtGui.QApplication.UnicodeUTF8)) + self.label_2.setText(QtGui.QApplication.translate("MainWindow", "Consumers", None, QtGui.QApplication.UnicodeUTF8)) + self.add.setText(QtGui.QApplication.translate("MainWindow", "+10", None, QtGui.QApplication.UnicodeUTF8)) _______________________________________________ Stackless-checkins mailing list Stackless-checkins at stackless.com http://www.stackless.com/mailman/listinfo/stackless-checkins From python-checkins at python.org Fri Mar 2 23:28:58 2007 From: python-checkins at python.org (richard.tew) Date: Fri, 2 Mar 2007 23:28:58 +0100 (CET) Subject: [Stackless-checkins] r54095 - stackless/sandbox/examples/twisted/twisted_webserver.py Message-ID: <20070302222858.EE6E91E4005@bag.python.org> Author: richard.tew Date: Fri Mar 2 23:28:57 2007 New Revision: 54095 Added: stackless/sandbox/examples/twisted/twisted_webserver.py - copied unchanged from r54094, stackless/sandbox/examples/twisted_webserver.py Log: made a copy _______________________________________________ Stackless-checkins mailing list Stackless-checkins at stackless.com http://www.stackless.com/mailman/listinfo/stackless-checkins From python-checkins at python.org Sat Mar 3 15:56:25 2007 From: python-checkins at python.org (richard.tew) Date: Sat, 3 Mar 2007 15:56:25 +0100 (CET) Subject: [Stackless-checkins] r54106 - stackless/sandbox/examples/webserver.py Message-ID: <20070303145625.AF5221E4008@bag.python.org> Author: richard.tew Date: Sat Mar 3 15:56:25 2007 New Revision: 54106 Added: stackless/sandbox/examples/webserver.py Log: An example which adapts the standard library module BaseHTTPServer to handle concurrent requests each on their own tasklet (as opposed to using the ThreadingMixIn from the SocketServer module). Added: stackless/sandbox/examples/webserver.py ============================================================================== --- (empty file) +++ stackless/sandbox/examples/webserver.py Sat Mar 3 15:56:25 2007 @@ -0,0 +1,72 @@ +# +# An example which adapts the standard library module BaseHTTPServer to +# handle concurrent requests each on their own tasklet (as opposed to +# using the ThreadingMixIn from the SocketServer module). +# +# Author: Richard Tew +# +# This code was written to serve as an example of Stackless Python usage. +# Feel free to email me with any questions, comments, or suggestions for +# improvement. +# +# But a better place to discuss Stackless Python related matters is the +# mailing list: +# +# http://www.tismer.com/mailman/listinfo/stackless +# + +# Monkeypatch in the stacklesssocket module. +import sys +import stacklesssocket +sys.modules["socket"] = stacklesssocket + +import stackless +from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer + +body = """ + + +StacklessHTTPServer page + + +Nothing to see here, move along.. + + +""" + +class RequestHandler(BaseHTTPRequestHandler): + # Respect keep alive requests. + protocol_version = "HTTP/1.1" + + def do_GET(self): + self.send_response(200) + self.send_header("Content-type", "text/html") + self.send_header("Content-Length", len(body)) + self.end_headers() + + self.wfile.write(body) + + +class StacklessHTTPServer(HTTPServer): + def handle_request(self): + try: + request, client_address = self.get_request() + except socket.error: + return + stackless.tasklet(self.handle_request_tasklet)(request, client_address) + + def handle_request_tasklet(self, request, client_address): + if self.verify_request(request, client_address): + try: + self.process_request(request, client_address) + except: + self.handle_error(request, client_address) + self.close_request(request) + +def Run(): + server = StacklessHTTPServer(('', 80), RequestHandler) + server.serve_forever() + +if __name__ == "__main__": + stackless.tasklet(Run)() + stackless.run() _______________________________________________ Stackless-checkins mailing list Stackless-checkins at stackless.com http://www.stackless.com/mailman/listinfo/stackless-checkins From python-checkins at python.org Fri Mar 2 23:28:00 2007 From: python-checkins at python.org (richard.tew) Date: Fri, 2 Mar 2007 23:28:00 +0100 (CET) Subject: [Stackless-checkins] r54093 - stackless/sandbox/examples/twisted Message-ID: <20070302222800.814B91E4005@bag.python.org> Author: richard.tew Date: Fri Mar 2 23:27:56 2007 New Revision: 54093 Added: stackless/sandbox/examples/twisted/ Log: Added Twisted directory. _______________________________________________ Stackless-checkins mailing list Stackless-checkins at stackless.com http://www.stackless.com/mailman/listinfo/stackless-checkins From python-checkins at python.org Fri Mar 30 21:35:24 2007 From: python-checkins at python.org (richard.tew) Date: Fri, 30 Mar 2007 21:35:24 +0200 (CEST) Subject: [Stackless-checkins] r54626 - stackless/branches/release25-maint/Stackless/core/stackless_impl.h Message-ID: <20070330193524.E27EC1E400F@bag.python.org> Author: richard.tew Date: Fri Mar 30 21:35:22 2007 New Revision: 54626 Modified: stackless/branches/release25-maint/Stackless/core/stackless_impl.h Log: Fix the prototype for PyEval_EvalFrameEx_slp to be properly declared as an API function. Modified: stackless/branches/release25-maint/Stackless/core/stackless_impl.h ============================================================================== --- stackless/branches/release25-maint/Stackless/core/stackless_impl.h (original) +++ stackless/branches/release25-maint/Stackless/core/stackless_impl.h Fri Mar 30 21:35:22 2007 @@ -18,7 +18,7 @@ #include "pickling/prickelpit.h" #undef STACKLESS_SPY -/* +/* * if a platform wants to support self-inspection via _peek, * it must provide a function or macro CANNOT_READ_MEM(adr, len) * which allows to spy at memory without causing exceptions. @@ -70,7 +70,7 @@ PyAPI_FUNC(PyObject *) slp_eval_frame(struct _frame *f); /* the frame dispatcher */ -PyAPI_FUNC(PyObject *) slp_frame_dispatch(PyFrameObject *f, +PyAPI_FUNC(PyObject *) slp_frame_dispatch(PyFrameObject *f, PyFrameObject *stopframe, int exc, PyObject *retval); @@ -79,7 +79,7 @@ /* the now exported eval_frame */ PyAPI_FUNC(PyObject *) PyEval_EvalFrame(struct _frame *f); -PyObject * PyEval_EvalFrameEx_slp(struct _frame *, int, PyObject *); +PyAPI_FUNC(PyObject *) PyEval_EvalFrameEx_slp(struct _frame *, int, PyObject *); /* eval_frame with stack overflow, triggered there with a macro */ PyAPI_FUNC(PyObject *) slp_eval_frame_newstack(struct _frame *f, int throwflag, PyObject *retval); @@ -209,7 +209,7 @@ move the slp_try_stackless flag into the local variable "stackless". PROMOTE(func) - + if stackless was set and the function's type has set Py_TPFLAGS_HAVE_STACKLESS_CALL, then this flag will be put back into slp_try_stackless, and we expect that the @@ -240,7 +240,7 @@ make sure that slp_ry_stackless was cleared. This debug feature tries to ensure that no unexpected nonrecursive call can happen. - + Some functions which are known to be stackless by nature just use the PROPOSE macros. They do not care about prior state. Most of them are used in ceval.c and other contexts which are @@ -435,12 +435,12 @@ PyAPI_FUNC(int) slp_int_wrapper(PyObject *retval); PyAPI_FUNC(int) slp_current_wrapper(int(*func)(PyTaskletObject*), PyTaskletObject *task); -PyAPI_FUNC(int) slp_resurrect_and_kill(PyObject *self, +PyAPI_FUNC(int) slp_resurrect_and_kill(PyObject *self, void(*killer)(PyObject *)); /* stackless pickling support */ -PyAPI_FUNC(int) slp_safe_pickling(int(*save)(PyObject *, PyObject *, int), +PyAPI_FUNC(int) slp_safe_pickling(int(*save)(PyObject *, PyObject *, int), PyObject *self, PyObject *args, int pers_save); _______________________________________________ Stackless-checkins mailing list Stackless-checkins at stackless.com http://www.stackless.com/mailman/listinfo/stackless-checkins From python-checkins at python.org Fri Mar 2 23:29:38 2007 From: python-checkins at python.org (richard.tew) Date: Fri, 2 Mar 2007 23:29:38 +0100 (CET) Subject: [Stackless-checkins] r54097 - stackless/sandbox/examples/twisted/twisted_yield.py Message-ID: <20070302222938.373F21E4005@bag.python.org> Author: richard.tew Date: Fri Mar 2 23:29:35 2007 New Revision: 54097 Added: stackless/sandbox/examples/twisted/twisted_yield.py - copied unchanged from r54096, stackless/sandbox/examples/twisted_yield.py Log: made a copy _______________________________________________ Stackless-checkins mailing list Stackless-checkins at stackless.com http://www.stackless.com/mailman/listinfo/stackless-checkins From python-checkins at python.org Fri Mar 2 23:29:18 2007 From: python-checkins at python.org (richard.tew) Date: Fri, 2 Mar 2007 23:29:18 +0100 (CET) Subject: [Stackless-checkins] r54096 - stackless/sandbox/examples/twisted/twisted_webserver_threaded.py Message-ID: <20070302222918.EAF901E4005@bag.python.org> Author: richard.tew Date: Fri Mar 2 23:29:17 2007 New Revision: 54096 Added: stackless/sandbox/examples/twisted/twisted_webserver_threaded.py - copied unchanged from r54095, stackless/sandbox/examples/twisted_webserver_threaded.py Log: made a copy _______________________________________________ Stackless-checkins mailing list Stackless-checkins at stackless.com http://www.stackless.com/mailman/listinfo/stackless-checkins From python-checkins at python.org Fri Mar 2 23:29:55 2007 From: python-checkins at python.org (richard.tew) Date: Fri, 2 Mar 2007 23:29:55 +0100 (CET) Subject: [Stackless-checkins] r54098 - stackless/sandbox/examples/twisted/twisted_yielddefer.py Message-ID: <20070302222955.DE6DF1E4005@bag.python.org> Author: richard.tew Date: Fri Mar 2 23:29:54 2007 New Revision: 54098 Added: stackless/sandbox/examples/twisted/twisted_yielddefer.py - copied unchanged from r54097, stackless/sandbox/examples/twisted_yielddefer.py Log: made a copy _______________________________________________ Stackless-checkins mailing list Stackless-checkins at stackless.com http://www.stackless.com/mailman/listinfo/stackless-checkins From mailman at stackless.com Sat Mar 3 12:04:20 2007 From: mailman at stackless.com (mailman at stackless.com) Date: Sat, 03 Mar 2007 12:04:20 +0100 Subject: Bounce action notification Message-ID: This is a Mailman mailing list bounce action notice: List: Stackless-checkins Member: chris at swellsoft.com Action: Subscription disabled. Reason: Excessive or fatal bounces. The triggering bounce notice is attached below. Questions? Contact the Mailman site administrator at mailman at stackless.com. -------------- next part -------------- An embedded message was scrubbed... From: Mail Delivery System Subject: Mail delivery failed: returning message to sender Date: Sat, 03 Mar 2007 12:03:16 +0100 Size: 22575 Url: http://www.stackless.com/pipermail/stackless-checkins/attachments/20070303/f32d35e4/attachment.eml From python-checkins at python.org Fri Mar 2 18:42:22 2007 From: python-checkins at python.org (richard.tew) Date: Fri, 2 Mar 2007 18:42:22 +0100 (CET) Subject: [Stackless-checkins] r54081 - stackless/sandbox/examples/twisted_webserver.py stackless/sandbox/examples/twisted_webserver_threaded.py Message-ID: <20070302174222.6D0C91E4008@bag.python.org> Author: richard.tew Date: Fri Mar 2 18:42:17 2007 New Revision: 54081 Added: stackless/sandbox/examples/twisted_webserver.py stackless/sandbox/examples/twisted_webserver_threaded.py Log: Added Andrew Francis' Twisted/Stackless examples. Added: stackless/sandbox/examples/twisted_webserver.py ============================================================================== --- (empty file) +++ stackless/sandbox/examples/twisted_webserver.py Fri Mar 2 18:42:17 2007 @@ -0,0 +1,111 @@ +#!/usr/bin/env python +""" +Webserver.py +Andrew Francis +March 1st, 2007 + +Example of Twisted and Stackless integration that +blocks. + +The server listens on http://localhost:8000 + +The programme is fine for many purposes. However there is a +flaw. Whenever the server tasklet blocks, it blocks the entire +programme. Ideally other tasklets, such as the Tick tasklet should +run while the server tasklet waits for connections. +""" + +# If you have any questions related to this example: +# +# - If they are related to how Twisted works, please contact the +# Twisted mailing list: +# +# http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python +# +# - If they are related to how Stackless works, please contact +# the Stackless mailing list: +# +# http://www.tismer.com/mailman/listinfo/stackless +# +# Otherwise if they are related to how Twisted works in conjunction with +# Stackless, please contact the Stackless mailing list: +# +# http://www.tismer.com/mailman/listinfo/stackless + +import time +import stackless +from twisted.web import http + +class Server(object): + + def execute(self, port, requestChannel): + MyRequestHandler.requestChannel = requestChannel + reactor.listenTCP(port, MyHttpFactory()) + reactor.run() + + +class Cgi(object): + def __init__(self, name, channel): + self.name = name + self.channel = channel + self.count = 0 + return + + def execute(self): + while (1): + + replyChannel = self.channel.receive() + replyChannel.send("" + \ + self.name + "count :" + str(self.count) + \ + "") + + self.count = self.count + 1 + stackless.schedule() + + +def tick(): + count = 0 + while (1): + print "tick: ", count + count += 1 + stackless.schedule() + + + +class MyRequestHandler(http.Request): + + def process(self): + """ + send back a unique channel that identifies the request handler + """ + replyChannel = stackless.channel() + MyRequestHandler.requestChannel.send(replyChannel) + result = replyChannel.receive() + self.write(result) + self.finish() + + +class MyHttp(http.HTTPChannel): + requestFactory = MyRequestHandler + + +class MyHttpFactory(http.HTTPFactory): + protocol = MyHttp + + +if __name__ == "__main__": + from twisted.internet import reactor + + channel = stackless.channel() + + cgiTasklet = Cgi("cgiTasklet-1", channel) + server = Server() + + stackless.tasklet(cgiTasklet.execute)() + stackless.tasklet(server.execute)(8000, channel) + print "Web Server started" + stackless.tasklet(tick)() + + print "entering main loop" + while (stackless.getruncount() > 1): + stackless.schedule() \ No newline at end of file Added: stackless/sandbox/examples/twisted_webserver_threaded.py ============================================================================== --- (empty file) +++ stackless/sandbox/examples/twisted_webserver_threaded.py Fri Mar 2 18:42:17 2007 @@ -0,0 +1,127 @@ +#!/usr/bin/env python +""" +ThreadedWebserver.py +Andrew Francis +March 1st, 2007 + +Example of Twisted and Stackless integration that allows non-blocking +tasklets to execute + +The server listens on http://localhost:8000 + +Unlike the previous example, ThreadedWebserver runs Stackless in a +separate thread. While Twisted is blocked waiting for connections, +the tick tasklet (or any other tasklet) can execute. + +As per Carlos's de Paula's observation, a time.sleep is included to +increase performance. I suspect the Global interpreter lock is playing +a role. On my machine time.sleep(.01) is fine. at .001, the server will +fail after multiple uses. +""" + +# If you have any questions related to this example: +# +# - If they are related to how Twisted works, please contact the +# Twisted mailing list: +# +# http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python +# +# - If they are related to how Stackless works, please contact +# the Stackless mailing list: +# +# http://www.tismer.com/mailman/listinfo/stackless +# +# Otherwise if they are related to how Twisted works in conjunction with +# Stackless, please contact the Stackless mailing list: +# +# http://www.tismer.com/mailman/listinfo/stackless + +import time + +import stackless +from twisted.web import http + +class Server(object): + + def execute(self, port, requestChannel): + MyRequestHandler.channel = requestChannel + reactor.listenTCP(port, MyHttpFactory()) + reactor.run() + + +class Cgi(object): + def __init__(self, name, channel): + self.name = name + self.channel = channel + self.count = 0 + return + + def execute(self): + while (1): + + replyChannel = self.channel.receive() + replyChannel.send("" + \ + self.name + " count :" + str(self.count) + \ + "") + + self.count = self.count + 1 + stackless.schedule() + + +def tick(): + count = 0 + while (1): + count += 1 + print count + time.sleep(.005) + stackless.schedule() + + + +class MyRequestHandler(http.Request): + + def process(self): + replyChannel = stackless.channel() + channel.send(replyChannel) + result = replyChannel.receive() + self.write(result) + self.finish() + + +class MyHttp(http.HTTPChannel): + requestFactory = MyRequestHandler + + +class MyHttpFactory(http.HTTPFactory): + protocol = MyHttp + + +def stacklessThread(requestChannel): + + cgiTasklet = Cgi("cgiTasklet-1", requestChannel) + stackless.tasklet(cgiTasklet.execute)() + + """ + in this example, if the tick tasklet did not exist, + Stackless would complain about deadlock since the + last runnable tasklet (cgiTasklet) would be blocked + """ + stackless.tasklet(tick)() + + while (stackless.getruncount() > 1): + stackless.schedule() + + +if __name__ == "__main__": + from twisted.internet import reactor + + print "ThreadedWebserver" + + channel = stackless.channel() + reactor.callInThread(stacklessThread,channel) + Server().execute(8000, channel) + reactor.run() + + + + \ No newline at end of file _______________________________________________ Stackless-checkins mailing list Stackless-checkins at stackless.com http://www.stackless.com/mailman/listinfo/stackless-checkins From mailman-bounces at stackless.com Sat Mar 24 09:00:11 2007 From: mailman-bounces at stackless.com (mailman-bounces at stackless.com) Date: Sat, 24 Mar 2007 09:00:11 +0100 Subject: Stackless-checkins Abbestellungbenachrichtigung Message-ID: chris at swellsoft.com has been removed from Stackless-checkins. From python-checkins at python.org Fri Mar 2 23:28:37 2007 From: python-checkins at python.org (richard.tew) Date: Fri, 2 Mar 2007 23:28:37 +0100 (CET) Subject: [Stackless-checkins] r54094 - stackless/sandbox/examples/twisted/twisted_timer.py Message-ID: <20070302222837.BFB911E4005@bag.python.org> Author: richard.tew Date: Fri Mar 2 23:28:37 2007 New Revision: 54094 Added: stackless/sandbox/examples/twisted/twisted_timer.py - copied unchanged from r54093, stackless/sandbox/examples/twisted_timer.py Log: made a copy _______________________________________________ Stackless-checkins mailing list Stackless-checkins at stackless.com http://www.stackless.com/mailman/listinfo/stackless-checkins From mailman-bounces at stackless.com Sat Mar 24 22:43:00 2007 From: mailman-bounces at stackless.com (mailman-bounces at stackless.com) Date: Sat, 24 Mar 2007 22:43:00 +0100 Subject: Stackless-checkins unsubscribe notification Message-ID: stackless at ada.majorek.org has been removed from Stackless-checkins. From python-checkins at python.org Fri Mar 2 23:30:49 2007 From: python-checkins at python.org (richard.tew) Date: Fri, 2 Mar 2007 23:30:49 +0100 (CET) Subject: [Stackless-checkins] r54099 - stackless/sandbox/examples/twisted_timer.py stackless/sandbox/examples/twisted_webserver.py stackless/sandbox/examples/twisted_webserver_threaded.py stackless/sandbox/examples/twisted_yield.py stackless/sandbox/examples/twisted_yielddefer.py Message-ID: <20070302223049.941B31E4005@bag.python.org> Author: richard.tew Date: Fri Mar 2 23:30:49 2007 New Revision: 54099 Removed: stackless/sandbox/examples/twisted_timer.py stackless/sandbox/examples/twisted_webserver.py stackless/sandbox/examples/twisted_webserver_threaded.py stackless/sandbox/examples/twisted_yield.py stackless/sandbox/examples/twisted_yielddefer.py Log: Removing Twisted examples which were branched into the 'twisted' directory. Deleted: /stackless/sandbox/examples/twisted_timer.py ============================================================================== --- /stackless/sandbox/examples/twisted_timer.py Fri Mar 2 23:30:49 2007 +++ (empty file) @@ -1,76 +0,0 @@ -# Twisted and Stackless - example 1 -# -# In this example, most of the time is spent in the twisted event loop. This -# approach allows you to control the granularity of tasklet execution based on -# time. At 30fps, a timer executes that schedules stackless tasklets to run - a -# simple tasklet just prints "do-op". -# -# by Greg Hazel -# -# If you have any questions related to this example: -# -# - If they are related to how Twisted works, please contact the -# Twisted mailing list: -# -# http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python -# -# - If they are related to how Stackless works, please contact -# the Stackless mailing list: -# -# http://www.tismer.com/mailman/listinfo/stackless -# -# Otherwise if they are related to how Twisted works in conjunction with -# Stackless, please contact the Stackless mailing list: -# -# http://www.tismer.com/mailman/listinfo/stackless - -import time -import stackless -from twisted.internet import task, reactor - -# a few globals for fun -ideal_fps = 30.0 -fps = 0 -clock = getattr(time, 'clock', time.time) -last_time = clock() - - -def frame(): - global fps, last_time - - # a silly fps counter - this_time = clock() - d = 1.0 / (this_time - last_time) - fps = (fps + d) / 2.0 - last_time = this_time - print fps - - # allow tasklets to run - stackless.schedule() - -# start the timer -t = task.LoopingCall(frame) -t.start(1.0/ideal_fps) - - -def tasklet(): - - while True: - # complicated operation with side-effects - print 'do-op' - - # allow the reactor to resume - stackless.schedule() - - # don't loop forever - if not reactor.running: - break - - -# start the simple tasklet -stackless.tasklet(tasklet)() - -# start the reactor -stackless.tasklet(reactor.run)() -# start the stackless scheduler -stackless.run() Deleted: /stackless/sandbox/examples/twisted_webserver.py ============================================================================== --- /stackless/sandbox/examples/twisted_webserver.py Fri Mar 2 23:30:49 2007 +++ (empty file) @@ -1,111 +0,0 @@ -#!/usr/bin/env python -""" -Webserver.py -Andrew Francis -March 1st, 2007 - -Example of Twisted and Stackless integration that -blocks. - -The server listens on http://localhost:8000 - -The programme is fine for many purposes. However there is a -flaw. Whenever the server tasklet blocks, it blocks the entire -programme. Ideally other tasklets, such as the Tick tasklet should -run while the server tasklet waits for connections. -""" - -# If you have any questions related to this example: -# -# - If they are related to how Twisted works, please contact the -# Twisted mailing list: -# -# http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python -# -# - If they are related to how Stackless works, please contact -# the Stackless mailing list: -# -# http://www.tismer.com/mailman/listinfo/stackless -# -# Otherwise if they are related to how Twisted works in conjunction with -# Stackless, please contact the Stackless mailing list: -# -# http://www.tismer.com/mailman/listinfo/stackless - -import time -import stackless -from twisted.web import http - -class Server(object): - - def execute(self, port, requestChannel): - MyRequestHandler.requestChannel = requestChannel - reactor.listenTCP(port, MyHttpFactory()) - reactor.run() - - -class Cgi(object): - def __init__(self, name, channel): - self.name = name - self.channel = channel - self.count = 0 - return - - def execute(self): - while (1): - - replyChannel = self.channel.receive() - replyChannel.send("" + \ - self.name + "count :" + str(self.count) + \ - "") - - self.count = self.count + 1 - stackless.schedule() - - -def tick(): - count = 0 - while (1): - print "tick: ", count - count += 1 - stackless.schedule() - - - -class MyRequestHandler(http.Request): - - def process(self): - """ - send back a unique channel that identifies the request handler - """ - replyChannel = stackless.channel() - MyRequestHandler.requestChannel.send(replyChannel) - result = replyChannel.receive() - self.write(result) - self.finish() - - -class MyHttp(http.HTTPChannel): - requestFactory = MyRequestHandler - - -class MyHttpFactory(http.HTTPFactory): - protocol = MyHttp - - -if __name__ == "__main__": - from twisted.internet import reactor - - channel = stackless.channel() - - cgiTasklet = Cgi("cgiTasklet-1", channel) - server = Server() - - stackless.tasklet(cgiTasklet.execute)() - stackless.tasklet(server.execute)(8000, channel) - print "Web Server started" - stackless.tasklet(tick)() - - print "entering main loop" - while (stackless.getruncount() > 1): - stackless.schedule() \ No newline at end of file Deleted: /stackless/sandbox/examples/twisted_webserver_threaded.py ============================================================================== --- /stackless/sandbox/examples/twisted_webserver_threaded.py Fri Mar 2 23:30:49 2007 +++ (empty file) @@ -1,127 +0,0 @@ -#!/usr/bin/env python -""" -ThreadedWebserver.py -Andrew Francis -March 1st, 2007 - -Example of Twisted and Stackless integration that allows non-blocking -tasklets to execute - -The server listens on http://localhost:8000 - -Unlike the previous example, ThreadedWebserver runs Stackless in a -separate thread. While Twisted is blocked waiting for connections, -the tick tasklet (or any other tasklet) can execute. - -As per Carlos's de Paula's observation, a time.sleep is included to -increase performance. I suspect the Global interpreter lock is playing -a role. On my machine time.sleep(.01) is fine. at .001, the server will -fail after multiple uses. -""" - -# If you have any questions related to this example: -# -# - If they are related to how Twisted works, please contact the -# Twisted mailing list: -# -# http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python -# -# - If they are related to how Stackless works, please contact -# the Stackless mailing list: -# -# http://www.tismer.com/mailman/listinfo/stackless -# -# Otherwise if they are related to how Twisted works in conjunction with -# Stackless, please contact the Stackless mailing list: -# -# http://www.tismer.com/mailman/listinfo/stackless - -import time - -import stackless -from twisted.web import http - -class Server(object): - - def execute(self, port, requestChannel): - MyRequestHandler.channel = requestChannel - reactor.listenTCP(port, MyHttpFactory()) - reactor.run() - - -class Cgi(object): - def __init__(self, name, channel): - self.name = name - self.channel = channel - self.count = 0 - return - - def execute(self): - while (1): - - replyChannel = self.channel.receive() - replyChannel.send("" + \ - self.name + " count :" + str(self.count) + \ - "") - - self.count = self.count + 1 - stackless.schedule() - - -def tick(): - count = 0 - while (1): - count += 1 - print count - time.sleep(.005) - stackless.schedule() - - - -class MyRequestHandler(http.Request): - - def process(self): - replyChannel = stackless.channel() - channel.send(replyChannel) - result = replyChannel.receive() - self.write(result) - self.finish() - - -class MyHttp(http.HTTPChannel): - requestFactory = MyRequestHandler - - -class MyHttpFactory(http.HTTPFactory): - protocol = MyHttp - - -def stacklessThread(requestChannel): - - cgiTasklet = Cgi("cgiTasklet-1", requestChannel) - stackless.tasklet(cgiTasklet.execute)() - - """ - in this example, if the tick tasklet did not exist, - Stackless would complain about deadlock since the - last runnable tasklet (cgiTasklet) would be blocked - """ - stackless.tasklet(tick)() - - while (stackless.getruncount() > 1): - stackless.schedule() - - -if __name__ == "__main__": - from twisted.internet import reactor - - print "ThreadedWebserver" - - channel = stackless.channel() - reactor.callInThread(stacklessThread,channel) - Server().execute(8000, channel) - reactor.run() - - - - \ No newline at end of file Deleted: /stackless/sandbox/examples/twisted_yield.py ============================================================================== --- /stackless/sandbox/examples/twisted_yield.py Fri Mar 2 23:30:49 2007 +++ (empty file) @@ -1,82 +0,0 @@ -# Twisted and Stackless - example 2 -# -# In this example, a large portion of the time is spent in stackless. This -# approach allows you to control the granularity of tasklet execution based on -# cooperative yield points in the tasklet. At 30fps, a timer executes that -# prints the fps. A simple tasklet just prints "." and yields to the reactor. -# The reactor processes all pending events, then reschedules the tasklet. -# -# This example eats a lot of cpu, because no time is spent blocking - the -# control is constantly being passed back and forth between the reactor and -# stackless. -# -# by Greg Hazel -# -# If you have any questions related to this example: -# -# - If they are related to how Twisted works, please contact the -# Twisted mailing list: -# -# http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python -# -# - If they are related to how Stackless works, please contact -# the Stackless mailing list: -# -# http://www.tismer.com/mailman/listinfo/stackless -# -# Otherwise if they are related to how Twisted works in conjunction with -# Stackless, please contact the Stackless mailing list: -# -# http://www.tismer.com/mailman/listinfo/stackless - - -import sys -import time -import stackless -from twisted.internet import task, reactor - -# a few globals for fun -ideal_fps = 30.0 -fps = 0 -clock = getattr(time, 'clock', time.time) -last_time = clock() - - -def frame(): - global fps, last_time - - # a silly fps counter - this_time = clock() - d = 1.0 / (this_time - last_time) - fps = (fps + d) / 2.0 - last_time = this_time - print '\n', fps - - -# start the timer -t = task.LoopingCall(frame) -t.start(1.0/ideal_fps) - - -def tasklet(): - - while True: - # complicated operation with side-effects - sys.stdout.write('.') - - # allow the reactor to run all pending events, then come back - reactor.callLater(0, stackless.schedule) - stackless.schedule() - - # don't loop forever - if not reactor.running: - break - - -# start the simple tasklet -stackless.tasklet(tasklet)() - -# start the reactor -stackless.tasklet(reactor.run)() -# start the stackless scheduler -stackless.run() Deleted: /stackless/sandbox/examples/twisted_yielddefer.py ============================================================================== --- /stackless/sandbox/examples/twisted_yielddefer.py Fri Mar 2 23:30:49 2007 +++ (empty file) @@ -1,144 +0,0 @@ -# Twisted and Stackless - example 3 -# -# In this example, most of the time is spent in the twisted event loop. This -# approach allows you to control the granularity of tasklet execution based on -# deferred operations a tasklet waits on. At 30fps, a timer executes that -# prints the fps. A simple tasklet begins a deferred operation, and waits for -# the result. During that time, control is returned to the reactor. -# -# Because of the possibility that a deferred operation completes immediately, -# a channel subclass is used to hold the value and return it without any -# rescheduling. stackless.channel.send() would otherwise block the tasklet -# before it could call stackless.channel.receive(). -# -# by Greg Hazel -# -# If you have any questions related to this example: -# -# - If they are related to how Twisted works, please contact the -# Twisted mailing list: -# -# http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python -# -# - If they are related to how Stackless works, please contact -# the Stackless mailing list: -# -# http://www.tismer.com/mailman/listinfo/stackless -# -# Otherwise if they are related to how Twisted works in conjunction with -# Stackless, please contact the Stackless mailing list: -# -# http://www.tismer.com/mailman/listinfo/stackless - -import time -import stackless -from twisted.internet import task, reactor, defer -from twisted.python import failure - -# a few globals for fun -ideal_fps = 30.0 -fps = 0 -clock = getattr(time, 'clock', time.time) -last_time = clock() - - -def frame(): - global fps, last_time - - # a silly fps counter - this_time = clock() - d = 1.0 / (this_time - last_time) - fps = (fps + d) / 2.0 - last_time = this_time - print fps - - -# start the timer -t = task.LoopingCall(frame) -t.start(1.0/ideal_fps) - - -# a fake operation that returns a defered -def deferredOp(): - - df = defer.Deferred() - - # complete in 0.5 seconds - reactor.callLater(0.5, df.callback, "result!") - # a deferred that completed already - #df.callback("result!") - - # we could also fake an error - #reactor.callLater(0.5, df.errback, failure.Failure(Exception("failed"))) - # a deferred that failed already - #df.errback(failure.Failure(Exception("failed"))) - - return df - - -# a stackless channel which can hold a single value without scheduling. -# handy for tasklets that might send data to themselves before calling receive. -class NWChannel(stackless.channel): - - def send_nowait(self, v): - if self.balance == 0: - self.value = v - else: - self.send(v) - - def send_exception_nowait(self, type, value): - if self.balance == 0: - self.exc = (type, value) - else: - self.send_exception(type, value) - - def receive(self): - if hasattr(self, 'value'): - v = self.value - del self.value - return v - if hasattr(self, 'exc'): - type, value = self.exc - del self.exc - raise type, value - return stackless.channel.receive(self) - - -def good(r, me, return_channel): - return_channel.send_nowait(r) - # if the deferred is called back immediately, this function will be called - # from the original tasklet. no need to reschedule. - if stackless.getcurrent() != me: - stackless.schedule() - -def bad(f, me, return_channel): - return_channel.send_exception_nowait(f.type, f.value) - # if the deferred fails immediately, this function will be called - # from the original tasklet. no need to reschedule. - if stackless.getcurrent() != me: - stackless.schedule() - -def tasklet(): - return_channel = NWChannel() - me = stackless.getcurrent() - - while True: - # a deferred operation - df = deferredOp() - - df.addCallback(good, me, return_channel) - df.addErrback(bad, me, return_channel) - x = return_channel.receive() - print x - - # don't loop forever - if not reactor.running: - break - -# start the simple tasklet -stackless.tasklet(tasklet)() - -# start the reactor -stackless.tasklet(reactor.run)() -# start the stackless scheduler -stackless.run() _______________________________________________ Stackless-checkins mailing list Stackless-checkins at stackless.com http://www.stackless.com/mailman/listinfo/stackless-checkins From python-checkins at python.org Sat Mar 24 10:43:33 2007 From: python-checkins at python.org (richard.tew) Date: Sat, 24 Mar 2007 10:43:33 +0100 (CET) Subject: [Stackless-checkins] r54558 - in stackless/sandbox: examples/FILES_MOVED.README examples/channelWithReceiveTimeout.py examples/embedding/FILES_MOVED.README examples/embedding/dice1/FILES_MOVED.README examples/embedding/watchdog-c/FILES_MOVED.README examples/embedding/watchdog-cpp/FILES_MOVED.README examples/mud.py examples/pyqt/producer-consumer/producer_consumer.py examples/pyqt/producer-consumer/producer_consumer_ui.py examples/rpc.py examples/scheduleAlternative.py examples/scheduleNormal.py examples/stacklesssocket.py examples/threadchannels.py examples/threadscheduling.py examples/twisted/twisted_timer.py examples/twisted/twisted_webserver.py examples/twisted/twisted_webserver_threaded.py examples/twisted/twisted_yield.py examples/twisted/twisted_yielddefer.py examples/webserver.py libraries/FILES_MOVED.README Message-ID: <20070324094333.5A59E1E400F@bag.python.org> Author: richard.tew Date: Sat Mar 24 10:43:31 2007 New Revision: 54558 Added: stackless/sandbox/examples/FILES_MOVED.README stackless/sandbox/examples/embedding/FILES_MOVED.README stackless/sandbox/examples/embedding/dice1/FILES_MOVED.README stackless/sandbox/examples/embedding/watchdog-c/FILES_MOVED.README stackless/sandbox/examples/embedding/watchdog-cpp/FILES_MOVED.README stackless/sandbox/libraries/FILES_MOVED.README Modified: stackless/sandbox/examples/channelWithReceiveTimeout.py stackless/sandbox/examples/mud.py stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer.py stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer_ui.py stackless/sandbox/examples/rpc.py stackless/sandbox/examples/scheduleAlternative.py stackless/sandbox/examples/scheduleNormal.py stackless/sandbox/examples/stacklesssocket.py stackless/sandbox/examples/threadchannels.py stackless/sandbox/examples/threadscheduling.py stackless/sandbox/examples/twisted/twisted_timer.py stackless/sandbox/examples/twisted/twisted_webserver.py stackless/sandbox/examples/twisted/twisted_webserver_threaded.py stackless/sandbox/examples/twisted/twisted_yield.py stackless/sandbox/examples/twisted/twisted_yielddefer.py stackless/sandbox/examples/webserver.py Log: The examples and libraries directories are now part of the Stackless examples project located at Google project hosting. As there may be links out there to these files, I have replaced the contents of the Python ones with directions to the new versions. And elsewhere README files have been added to indicate the same. Added: stackless/sandbox/examples/FILES_MOVED.README ============================================================================== --- (empty file) +++ stackless/sandbox/examples/FILES_MOVED.README Sat Mar 24 10:43:31 2007 @@ -0,0 +1,17 @@ + +Hi, + +These examples and libraries are no longer maintained here. The versions +you find here, are possibly old and lack recent fixes. + +The new versions can be found here: + + http://code.google.com/p/stacklessexamples/wiki/StacklessExamples + +Please feel free to email the Stackless mailing list: + + http://www.stackless.com/mailman/listinfo/stackless + +Thanks, +Richard Tew. + Modified: stackless/sandbox/examples/channelWithReceiveTimeout.py ============================================================================== --- stackless/sandbox/examples/channelWithReceiveTimeout.py (original) +++ stackless/sandbox/examples/channelWithReceiveTimeout.py Sat Mar 24 10:43:31 2007 @@ -1,139 +1,17 @@ # -# One way of timing out tasklets waiting on a channel. +# Hi, # -# Author: Richard Tew +# These examples and libraries are no longer maintained here. The versions +# you find here, are possibly old and lack recent fixes. # -# This code was written to serve as an example of Stackless Python usage. -# Feel free to email me with any questions, comments, or suggestions for -# improvement. +# The new versions can be found here: +# +# http://code.google.com/p/stacklessexamples/wiki/StacklessExamples +# +# Please feel free to email the Stackless mailing list: +# +# http://www.stackless.com/mailman/listinfo/stackless +# +# Thanks, +# Richard Tew. # -# Limitations of this approach: -# -# - There is no need to know the order the tasklets are waiting on the -# channel because of the uniform expiration period so we can assume -# that the first to expire will be the first in line on the channel -# and we can remove it by sending an exception. -# - -import time, weakref -import stackless - -exitScheduler = False - -sleepingTasklets = [] - -# Utility functions for tasklets to call. - -def Sleep(secondsToWait): - """ Put the current tasklet to sleep for a number of seconds. """ - channel = stackless.channel() - endTime = time.time() + secondsToWait - sleepingTasklets.append((endTime, channel)) - sleepingTasklets.sort() - # Block until we get sent an awakening notification. - channel.receive() - -# Scheduler running related functions. - -def ManageSleepingTasklets(): - """ Awaken all tasklets which are due to be awakened. """ - while not exitScheduler: - while len(sleepingTasklets): - endTime = sleepingTasklets[0][0] - if endTime > time.time(): - break - channel = sleepingTasklets[0][1] - del sleepingTasklets[0] - # It does not matter what we send as it is not used. - channel.send(None) - stackless.schedule() - - -class ChannelWaitExpiration(Exception): - pass - -class TimeLimitedReceiveChannel(stackless.channel): - def __init__(self, *args, **kwargs): - self.expirySeconds = 5.0 - self.receiveAddTimes = [] - - stackless.channel.__init__(self, *args, **kwargs) - - def receive(self): - if self.balance > 0: - # We can return from this immediately. - return stackless.channel.receive(self) - - if self.balance == 0: - def ManageWaitingTasklets(c): - while c.balance < 0: - earliestExpirationTime = None - for timeAdded, tasklet in self.receiveAddTimes: - if not tasklet.blocked: - # This tasklet has already been removed but since - # it hasn't been scheduled yet it hasn't exited its - # call to our receive function and cleared out its - # entry. This can happen if the channel is configured - # to schedule waiting tasklets when they receive - # rather than running them immediately (i.e. via the - # 'preference' attribute). - continue - if timeAdded + self.expirySeconds < time.time(): - # This tasklet is guaranteed to be the first tasklet - # on the channel. - self.send_exception(ChannelWaitExpiration) - else: - # Otherwise note the time at which the next expiring - # tasklet expires so we can sleep until then. Since - # all expiration delays are the same amount of time - # from the period of addition, we can guess the - # earliest we will need to check next. - earliestExpirationTime = timeAdded + self.expirySeconds - break - # Wait until the earliest we will need to next check. - if earliestExpirationTime is None: - Sleep(self.expirySeconds) - else: - Sleep(time.time() - earliestExpirationTime) - stackless.tasklet(ManageWaitingTasklets)(self) - - t = time.time(), weakref.proxy(stackless.getcurrent()) - self.receiveAddTimes.append(t) - self.receiveAddTimes.sort() - - try: - ret = stackless.channel.receive(self) - self.receiveAddTimes.remove(t) - return ret - except: - # Any exception should be met with the same handling. - self.receiveAddTimes.remove(t) - raise - -def Run(): - c = TimeLimitedReceiveChannel() - - def Test(c): - global exitScheduler - t = time.time() - print "Waiting for %0.1f seconds" % c.expirySeconds - try: - c.receive() - except Exception, e: - if isinstance(e, ChannelWaitExpiration): - print "Exited receive, took %0.1f seconds" % (time.time() - t) - else: - print "Unexpected exit '%s', took %0.1f seconds" % (str(e), time.time() - t) - finally: - exitScheduler = True - - stackless.tasklet(Test)(c) - stackless.tasklet(ManageSleepingTasklets)() - - # This will run until there are no scheduled tasklets. But because we - # create one to manage the sleeping tasklets this will mean it will run - # indefinitely. - stackless.run() - -if __name__ == '__main__': - Run() Added: stackless/sandbox/examples/embedding/FILES_MOVED.README ============================================================================== --- (empty file) +++ stackless/sandbox/examples/embedding/FILES_MOVED.README Sat Mar 24 10:43:31 2007 @@ -0,0 +1,17 @@ + +Hi, + +These examples and libraries are no longer maintained here. The versions +you find here, are possibly old and lack recent fixes. + +The new versions can be found here: + + http://code.google.com/p/stacklessexamples/wiki/StacklessExamples + +Please feel free to email the Stackless mailing list: + + http://www.stackless.com/mailman/listinfo/stackless + +Thanks, +Richard Tew. + Added: stackless/sandbox/examples/embedding/dice1/FILES_MOVED.README ============================================================================== --- (empty file) +++ stackless/sandbox/examples/embedding/dice1/FILES_MOVED.README Sat Mar 24 10:43:31 2007 @@ -0,0 +1,17 @@ + +Hi, + +These examples and libraries are no longer maintained here. The versions +you find here, are possibly old and lack recent fixes. + +The new versions can be found here: + + http://code.google.com/p/stacklessexamples/wiki/StacklessExamples + +Please feel free to email the Stackless mailing list: + + http://www.stackless.com/mailman/listinfo/stackless + +Thanks, +Richard Tew. + Added: stackless/sandbox/examples/embedding/watchdog-c/FILES_MOVED.README ============================================================================== --- (empty file) +++ stackless/sandbox/examples/embedding/watchdog-c/FILES_MOVED.README Sat Mar 24 10:43:31 2007 @@ -0,0 +1,17 @@ + +Hi, + +These examples and libraries are no longer maintained here. The versions +you find here, are possibly old and lack recent fixes. + +The new versions can be found here: + + http://code.google.com/p/stacklessexamples/wiki/StacklessExamples + +Please feel free to email the Stackless mailing list: + + http://www.stackless.com/mailman/listinfo/stackless + +Thanks, +Richard Tew. + Added: stackless/sandbox/examples/embedding/watchdog-cpp/FILES_MOVED.README ============================================================================== --- (empty file) +++ stackless/sandbox/examples/embedding/watchdog-cpp/FILES_MOVED.README Sat Mar 24 10:43:31 2007 @@ -0,0 +1,17 @@ + +Hi, + +These examples and libraries are no longer maintained here. The versions +you find here, are possibly old and lack recent fixes. + +The new versions can be found here: + + http://code.google.com/p/stacklessexamples/wiki/StacklessExamples + +Please feel free to email the Stackless mailing list: + + http://www.stackless.com/mailman/listinfo/stackless + +Thanks, +Richard Tew. + Modified: stackless/sandbox/examples/mud.py ============================================================================== --- stackless/sandbox/examples/mud.py (original) +++ stackless/sandbox/examples/mud.py Sat Mar 24 10:43:31 2007 @@ -1,174 +1,17 @@ # -# A very simple MUD server based on the Stackless compatible sockets. +# Hi, # -# Author: Richard Tew +# These examples and libraries are no longer maintained here. The versions +# you find here, are possibly old and lack recent fixes. # -# This code was written to serve as an example of Stackless Python usage. -# Feel free to email me with any questions, comments, or suggestions for -# improvement. +# The new versions can be found here: +# +# http://code.google.com/p/stacklessexamples/wiki/StacklessExamples +# +# Please feel free to email the Stackless mailing list: # -# - Could possibly be even simpler if the TelnetConnection class were removed -# and read/readline were done locally to the MUD code. Then disconnection -# detection could be built into the stacklesssocket.dispatcher class. +# http://www.stackless.com/mailman/listinfo/stackless +# +# Thanks, +# Richard Tew. # - -import stackless -import stacklesssocket as socket -import random, time -import traceback - -class TelnetConnectionWrapper(socket.stacklesssocket): - connectionID = None - disconnectChannel = None - - def __init__(self, sock): - self.sock = sock - self.dispatcher = TelnetConnection(sock) - - def close(self): - # Notify the server. - if self.disconnectChannel is not None: - # This will not block. The channel is set to schedule - # receivers and return to the sender immediately. - self.disconnectChannel.send(self) - self.disconnectChannel = None - # Do the standard socket closure handling. But we can't - # call the underlying function as it doesn't exist on the - # superclass, and trying to call it there anyway won't get it - # routed through getattr. - self.dispatcher.close() - -class TelnetConnection(socket.dispatcher): - echo = False - - def read(self): # TELNET - ret = self.readChannel.receive() - if self.echo: - if ret == '\x08': - self.send(ret+" ") - self.send(ret) - return ret - - def readline(self): # TELNET - buf = self.readBuffer - - while True: - if buf.find('\r\n') > -1: - i = buf.index('\r\n') - ret = buf[:i+2] - self.readBuffer = buf[i+2:] - while '\x08' in ret: - i = ret.index('\x08') - if i == 0: - ret = ret[1:] - else: - ret = ret[:i-1]+ret[i+1:] - return ret - - buf += self.read() - -def RunServer(host, port): - listenSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - listenSocket.bind((host, port)) - listenSocket.listen(5) - - # Connecting sockets should be wrapped in TelnetConnection, rather than - # stacklesssocket.dispatcher (the default wrapper). - def wrap_accept_socket(currentSocket): - return TelnetConnectionWrapper(currentSocket) - listenSocket.wrap_accept_socket = wrap_accept_socket - - nextConnectionID = 1 - infoByConnectionID = {} - disconnectChannel = stackless.channel() - disconnectChannel.preference = 1 - stackless.tasklet(MonitorDisconnections)(disconnectChannel, infoByConnectionID) - - print "Accepting connections on", host, port - try: - while listenSocket.accepting: - clientSocket, clientAddress = listenSocket.accept() - clientSocket.disconnectChannel = disconnectChannel - clientSocket.connectionID = nextConnectionID - print "Received connection #", clientSocket.connectionID, "from", clientAddress - infoByConnectionID[clientSocket.connectionID] = clientAddress, clientSocket - nextConnectionID += 1 - stackless.tasklet(MonitorIncomingConnection)(clientSocket, clientAddress, infoByConnectionID) - stackless.schedule() - except socket.error: - print "RunServer.error" - traceback.print_exc() - print "RunServer.exit" - -def MonitorDisconnections(disconnectChannel, infoByConnectionID): - print "MonitorDisconnections" - try: - while True: - clientSocket = disconnectChannel.receive() - print "Received disconnection of #", clientSocket.connectionID, "from", infoByConnectionID[clientSocket.connectionID][0] - del infoByConnectionID[clientSocket.connectionID] - except socket.error: - print "MonitorDisconnections.error" - traceback.print_exc() - print "MonitorDisconnections.exit" - -def MonitorIncomingConnection(clientSocket, clientAddress, infoByConnectionID): - clientSocket.send("Welcome to a basic Stackless Python MUD server.\r\n") - try: - while clientSocket.connected: - clientSocket.send("> ") - line = clientSocket.readline()[:-2].strip() - words = [ word.strip() for word in line.split(" ") ] - verb = words[0] - - if verb == "look": - clientSocket.send("There are %d users connected:\r\n" % len(infoByConnectionID)) - clientSocket.send("Name\tHost\t\tPort\r\n") - clientSocket.send("-" * 40 +"\r\n") - for clientAddress2, clientSocket2 in infoByConnectionID.itervalues(): - clientSocket.send("Unknown\t"+ str(clientAddress2[0]) +"\t"+ str(clientAddress2[1]) +"\r\n") - elif verb == "say": - line = line[4:] - secondPartyPrefix = "Someone says: " - for clientAddress2, clientSocket2 in infoByConnectionID.itervalues(): - if clientSocket2 is clientSocket: - prefix = "You say: " - else: - prefix = secondPartyPrefix - clientSocket2.send(prefix + "\"%s\"\r\n" % line) - elif verb == "quit": - clientSocket.close() - elif verb == "help": - clientSocket.send("Commands:\r\n") - for verb in [ "look", "say", "quit", "help" ]: - clientSocket.send(" "+ verb +"\r\n") - else: - clientSocket.send("Unknown command. Type 'help' to see a list of available commands.\r\n") - - stackless.schedule() - except socket.error: - print "MonitorIncomingConnection.socket.error" - traceback.print_exc() - -if __name__ == "__main__": - host = "127.0.0.1" - port = 3000 - - # We do not want this to start as we will run it ourselves. - socket.managerRunning = True - - t = stackless.tasklet(RunServer)(host, port) - # ManageSockets will exit if there are no sockets existing, so - # by running this tasklet once, we will get the listen socket in - # place before we invoke ManageSockets to run. - t.run() - - try: - socket.ManageSockets() - except KeyboardInterrupt: - print "** Detected ctrl-c in the console" - except: - print "main error" - traceback.print_exc() - print "EXIT" Modified: stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer.py ============================================================================== --- stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer.py (original) +++ stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer.py Sat Mar 24 10:43:31 2007 @@ -1,261 +1,17 @@ # -# This is a small producer-consumer application integrated with PyQt. +# Hi, # -# Author: Carlos Eduardo de Paula +# These examples and libraries are no longer maintained here. The versions +# you find here, are possibly old and lack recent fixes. # -# The application uses no threads, all is done by tasklets, simple but -# is valid and can be extended. +# The new versions can be found here: +# +# http://code.google.com/p/stacklessexamples/wiki/StacklessExamples +# +# Please feel free to email the Stackless mailing list: +# +# http://www.stackless.com/mailman/listinfo/stackless +# +# Thanks, +# Richard Tew. # -# If you have any questions about this example, please feel free to -# contact the Stackless mailing list. You can subscribe at this -# address: -# -# http://www.tismer.com/mailman/listinfo/stackless -# - -import stackless -import time -import random -import sys -from PyQt4 import QtGui, QtCore - - -# Nice way to put the tasklet to sleep - from stackless.com wiki/Idioms -########################################################## -sleepingTasklets = [] - -def Sleep(secondsToWait): - channel = stackless.channel() - endTime = time.time() + secondsToWait - sleepingTasklets.append((endTime, channel)) - sleepingTasklets.sort() - # Block until we get sent an awakening notification. - channel.receive() - -def ManageSleepingTasklets(): - while 1: - if len(sleepingTasklets): - endTime = sleepingTasklets[0][0] - if endTime <= time.time(): - channel = sleepingTasklets[0][1] - del sleepingTasklets[0] - # We have to send something, but it doesn't matter what as it is not used. - channel.send(None) -# if len(sleepingTasklets) <= 0: time.sleep(endTime-time.time()) - #time.sleep(0.001) - stackless.schedule() - if len(sleepingTasklets) <= 0: stackless.getcurrent().kill() - -#stackless.tasklet(ManageSleepingTasklets)() - -########################################################## - -class Agent(object): - def __init__(self, name=None): - self.ch = stackless.channel() - self.name = name - self.items = 0 - self.kill = False - self.t = stackless.tasklet(self.runAction)() - - def runAction(self): - while not self.kill: - self.action() - - def action(self): - pass - -class Queue(object): - def __init__(self, name): - self.queue_start=0 - self.qt = self.queue_start - self.max_size = 100 - self.running = False - self.kill = False - self.produced = 0 - self.consumed = 0 - self.q_empty = 0 - self.q_full = 0 - self.producers = [] - self.consumers = [] - - def put(self, qty=1, who=None): - if self.qt+qty < self.max_size: - self.qt += qty - self.produced += 1 - else: - self.q_full += 1 - - def get(self, qty=1, who=None): - if self.qt >= qty: - self.qt -= qty - self.consumed += 1 - else: - self.q_empty += 1 - - -class Producer(Agent): - def __init__(self,name, queue): - Agent.__init__(self, name) - self.time = random.random() - self.items = 0 - self.queue = queue - self.queue.producers.append(self) - - def action(self): - while self.queue.running: - if self.queue.qt < 5: - Sleep(self.time) - else: - Sleep(self.time*2) - self.queue.put(1, self.name) - self.items += 1 - else: - Sleep(self.time) - -class Consumer(Agent): - def __init__(self, name, queue): - Agent.__init__(self, name) - self.time = random.random() - self.queue = queue - self.queue.consumers.append(self) - def action(self): - while self.queue.running: - self.queue.get(1, self.name) - self.items += 1 - if self.queue.qt < 5: - Sleep(self.time*2) - else: - Sleep(self.time) - else: - Sleep(self.time) - -########################################################################## - -class mainWindow(QtGui.QMainWindow): - def __init__(self): - QtGui.QMainWindow.__init__(self) - from producer_consumer_ui import Ui_MainWindow - # Set up the user interface from Designer. - self.ui = Ui_MainWindow() - self.ui.setupUi(self) - self.connect(self.ui.start, QtCore.SIGNAL("clicked()"),self.start) # <- Button - self.connect(self.ui.stop, QtCore.SIGNAL("clicked()"),self.stop) # <- Button - self.connect(self.ui.add, QtCore.SIGNAL("clicked()"),self.addtoqueue) # <- Button - self.connect(self.ui.addprod, QtCore.SIGNAL("clicked()"),self.addprod) # <- Button - self.connect(self.ui.addcons, QtCore.SIGNAL("clicked()"),self.addcons) # <- Button - - self.started = False - self.killtasks = False - self.q = Queue("Queue") - self.PID = 0 - self.CID = 0 - - def closeEvent(self, event): - self.killtasks = True - try: - for p in self.q.producers: - p.kill = True - for c in self.q.consumers: - c.kill = True - self.sleepMan.kill() - self.showReport() - except: pass - - def start(self): - if self.started: - self.q.running = True - self.ui.statusbar.showMessage("Running") - return - self.ui.statusbar.showMessage("Starting up...") - self.started = True - self.q.running = True - self.sleepMan = stackless.tasklet(ManageSleepingTasklets)() - self.monit = stackless.tasklet(self.monitor)() - self.ui.queue.setMaximum(self.q.max_size) - - for i in range(num_prod): - self.addprod() - - for i in range(num_cons): - self.addcons() - - self.ui.statusbar.showMessage("Running") - stackless.run() - - - def stop(self): - self.q.running = False - self.ui.statusbar.showMessage("Stopped") - - def addprod(self): - ID = self.PID - name = "P"+str(ID) - a = Producer(name, self.q) - self.PID += 1 - - def addcons(self): - ID = self.CID - name = "C"+str(ID) - a = Consumer(name, self.q) - self.CID += 1 - - def addtoqueue(self): - self.q.qt += 10 - - def monitor(self): - while not self.killtasks: - QtGui.QApplication.processEvents() - self.ui.queue.setValue(self.q.qt) - self.ui.prod.setText(str(len(self.q.producers))) - self.ui.cons.setText(str(len(self.q.consumers))) - Sleep(0.033) - #stackless.schedule() - - def showReport(self): - print - print "--------------------------" - for p in self.q.producers: - print "Producer", p.name , "produced: ", p.items, "items. Each production took: ", p.time - print - for c in self.q.consumers: - print "Consumer", c.name , "consumed: ", c.items, "items. Each consuption took: ", c.time - print "--------------------------" - print "Produced units: ", self.q.produced - print "Consumed units: ", self.q.consumed - print "Left in queue: ", self.q.qt - print - print "Queue became zero ", self.q.q_empty, " times." - print "Queue became full ", self.q.q_full, " times." - print - print "--------------------------" - - - -########################################################### - -num_prod = 10 # Number of starting producers -num_cons = 10 # Number of starting consumers - - -def main(args): - app = QtGui.QApplication(sys.argv) - mainwindow = mainWindow() - mainwindow.show() - sys.exit(app.exec_()) - -if __name__=="__main__": - main(sys.argv) - - - - - - - - - - - - - Modified: stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer_ui.py ============================================================================== --- stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer_ui.py (original) +++ stackless/sandbox/examples/pyqt/producer-consumer/producer_consumer_ui.py Sat Mar 24 10:43:31 2007 @@ -1,95 +1,17 @@ -# -*- coding: utf-8 -*- - -# Used by producer_consumer.py - -# Form implementation generated from reading ui file 'prodcon_ui.ui' # -# Created: Tue Aug 29 15:41:04 2006 -# by: PyQt4 UI code generator 4-snapshot-20060814 +# Hi, +# +# These examples and libraries are no longer maintained here. The versions +# you find here, are possibly old and lack recent fixes. +# +# The new versions can be found here: +# +# http://code.google.com/p/stacklessexamples/wiki/StacklessExamples +# +# Please feel free to email the Stackless mailing list: +# +# http://www.stackless.com/mailman/listinfo/stackless +# +# Thanks, +# Richard Tew. # -# WARNING! All changes made in this file will be lost! - -import sys -from PyQt4 import QtCore, QtGui - -class Ui_MainWindow(object): - def setupUi(self, MainWindow): - MainWindow.setObjectName("MainWindow") - MainWindow.resize(QtCore.QSize(QtCore.QRect(0,0,392,351).size()).expandedTo(MainWindow.minimumSizeHint())) - - self.centralwidget = QtGui.QWidget(MainWindow) - self.centralwidget.setObjectName("centralwidget") - - self.cons = QtGui.QLineEdit(self.centralwidget) - self.cons.setGeometry(QtCore.QRect(80,170,31,20)) - self.cons.setObjectName("cons") - - self.stop = QtGui.QPushButton(self.centralwidget) - self.stop.setGeometry(QtCore.QRect(60,70,75,23)) - self.stop.setObjectName("stop") - - self.start = QtGui.QPushButton(self.centralwidget) - self.start.setGeometry(QtCore.QRect(60,40,75,23)) - self.start.setObjectName("start") - - self.addprod = QtGui.QPushButton(self.centralwidget) - self.addprod.setGeometry(QtCore.QRect(270,160,75,23)) - self.addprod.setObjectName("addprod") - - self.label = QtGui.QLabel(self.centralwidget) - self.label.setGeometry(QtCore.QRect(20,150,48,14)) - self.label.setObjectName("label") - - self.prod = QtGui.QLineEdit(self.centralwidget) - self.prod.setGeometry(QtCore.QRect(80,150,31,20)) - self.prod.setObjectName("prod") - - self.addcons = QtGui.QPushButton(self.centralwidget) - self.addcons.setGeometry(QtCore.QRect(270,130,75,23)) - self.addcons.setObjectName("addcons") - - self.label_2 = QtGui.QLabel(self.centralwidget) - self.label_2.setGeometry(QtCore.QRect(20,171,53,14)) - self.label_2.setObjectName("label_2") - - self.add = QtGui.QPushButton(self.centralwidget) - self.add.setGeometry(QtCore.QRect(270,40,75,23)) - self.add.setObjectName("add") - - self.lcdNumber = QtGui.QLCDNumber(self.centralwidget) - self.lcdNumber.setGeometry(QtCore.QRect(170,40,64,23)) - self.lcdNumber.setObjectName("lcdNumber") - - self.queue = QtGui.QProgressBar(self.centralwidget) - self.queue.setGeometry(QtCore.QRect(190,80,22,211)) - self.queue.setMaximum(60) - self.queue.setProperty("value",QtCore.QVariant(0)) - self.queue.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) - self.queue.setOrientation(QtCore.Qt.Vertical) - self.queue.setInvertedAppearance(False) - self.queue.setTextDirection(QtGui.QProgressBar.TopToBottom) - self.queue.setObjectName("queue") - MainWindow.setCentralWidget(self.centralwidget) - - self.menubar = QtGui.QMenuBar(MainWindow) - self.menubar.setGeometry(QtCore.QRect(0,0,392,21)) - self.menubar.setObjectName("menubar") - MainWindow.setMenuBar(self.menubar) - - self.statusbar = QtGui.QStatusBar(MainWindow) - self.statusbar.setObjectName("statusbar") - MainWindow.setStatusBar(self.statusbar) - - self.retranslateUi(MainWindow) - QtCore.QObject.connect(self.queue,QtCore.SIGNAL("valueChanged(int)"),self.lcdNumber.display) - QtCore.QMetaObject.connectSlotsByName(MainWindow) - - def retranslateUi(self, MainWindow): - MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) - self.stop.setText(QtGui.QApplication.translate("MainWindow", "Stop", None, QtGui.QApplication.UnicodeUTF8)) - self.start.setText(QtGui.QApplication.translate("MainWindow", "Start", None, QtGui.QApplication.UnicodeUTF8)) - self.addprod.setText(QtGui.QApplication.translate("MainWindow", "+ Prod", None, QtGui.QApplication.UnicodeUTF8)) - self.label.setText(QtGui.QApplication.translate("MainWindow", "Producers", None, QtGui.QApplication.UnicodeUTF8)) - self.addcons.setText(QtGui.QApplication.translate("MainWindow", "+ Cons", None, QtGui.QApplication.UnicodeUTF8)) - self.label_2.setText(QtGui.QApplication.translate("MainWindow", "Consumers", None, QtGui.QApplication.UnicodeUTF8)) - self.add.setText(QtGui.QApplication.translate("MainWindow", "+10", None, QtGui.QApplication.UnicodeUTF8)) Modified: stackless/sandbox/examples/rpc.py ============================================================================== --- stackless/sandbox/examples/rpc.py (original) +++ stackless/sandbox/examples/rpc.py Sat Mar 24 10:43:31 2007 @@ -1,158 +1,17 @@ # -# Remote procedure calls over sockets with Stackless Python. +# Hi, # -# Author: Richard Tew +# These examples and libraries are no longer maintained here. The versions +# you find here, are possibly old and lack recent fixes. # -# This code was written to serve as an example of Stackless Python usage. -# Feel free to email me with any questions, comments, or suggestions for -# improvement. +# The new versions can be found here: +# +# http://code.google.com/p/stacklessexamples/wiki/StacklessExamples +# +# Please feel free to email the Stackless mailing list: # -# With just a page of code and the replacement socket module that is -# currently known as "stacklesssocket", it is possible to easily write -# a straightforward remote procedure call layer over a socket. +# http://www.stackless.com/mailman/listinfo/stackless +# +# Thanks, +# Richard Tew. # - -import stackless -import stacklesssocket as socket -import types, struct, cPickle - -class EndPoint: - def __init__(self, epSocket): - self.socket = epSocket - self.callID = 0 - self.channelsByCallID = {} - self.otherEnd = RemoteEndPoint(self) - - stackless.tasklet(self.ManageSocket)() - - def ManageSocket(self): - try: - self.ReceiveIncomingData() - except socket.error: - # Disconnection while blocking on a recv call. - return - - def ReceiveIncomingData(self): - while self.socket.connected: - data = self.socket.recv(struct.calcsize("I")) - dataLength = struct.unpack("I", data)[0] - data = self.socket.recv(dataLength) - packet = cPickle.loads(data) - callID = packet[1] - if packet[0]: - channel = self.channelsByCallID[callID] - del self.channelsByCallID[callID] - channel.send(packet[2]) - else: - ret = self.HandleIncomingCall(packet[2], packet[3], packet[4]) - self.SendPacket(True, callID, ret) - stackless.schedule() - - def HandleIncomingCall(self, name, args, kwargs): - if name.startswith("__") or hasattr(EndPoint, name): - return # Raise error? - method = getattr(self, name) - if type(method) is not types.MethodType: - return # Raise error? - return method(*args, **kwargs) - - def RemoteCall(self, methodInfo): - self.callID += 1 - callID = self.callID - - channel = self.channelsByCallID[callID] = stackless.channel() - self.SendPacket(False, callID, methodInfo.name, methodInfo.args, methodInfo.kwargs) - return channel.receive() - - def SendPacket(self, *bits): - data = cPickle.dumps(bits) - data = struct.pack("I", len(data)) + data - self.socket.send(data) - -class RemoteEndPoint: - def __init__(self, endpoint): - self.endpoint = endpoint - - def __getattr__(self, name): - return RemoteFunction(self.endpoint, name) - -class RemoteFunction: - def __init__(self, endpoint, name): - self.endpoint = endpoint - self.name = name - - def __call__(self, *args, **kwargs): - self.args = args - self.kwargs = kwargs - - return self.endpoint.RemoteCall(self) - -if __name__ == "__main__": - # This test/example code is a little artificial, but it should both - # adequately test the RPC code above and demonstrate how easy it is - # to write this sort of code with Stackless Python. - - class Server: - def __init__(self, address): - self.socket = listenSocket = socket.socket() - listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - listenSocket.bind(address) - listenSocket.listen(5) - - self.endPoints = [] - - stackless.tasklet(self.ManageSocket)(listenSocket) - - def ManageSocket(self, listenSocket): - try: - while listenSocket.accepting: - epSocket, clientAddress = listenSocket.accept() - endPoint = ServerEndPoint(epSocket) - self.endPoints.append(endPoint) - except socket.error: - pass # Listen socket disconnected. Our job is done. - - if listenSocket.accepting: - listenSocket.close() - self.endPoints = [] - - class ClientEndPoint(EndPoint): - def Hello(self): - return "Client Hello!" - - class ServerEndPoint(EndPoint): - def Hello(self): - return "Server Hello!" - - address = "127.0.0.1", 3000 - - # Start the server. - server = Server(address) - - clientSocket = socket.socket() - clientSocket.connect(address) - - # Then connect the client. - client = ClientEndPoint(clientSocket) - - def ClientTasklet(client, server, clientSocket): - # Tell the server hello. - ret = client.otherEnd.Hello() - print " CLIENT GOT", ret - - stackless.tasklet(ServerTasklet)(server) - while server.socket.connected: - stackless.schedule() - clientSocket.close() - - def ServerTasklet(server): - # Tell all the clients hello. - for endpoint in server.endPoints: - ret = endpoint.otherEnd.Hello() - print " SERVER GOT", ret, "FROM CLIENT" - server.socket.close() - - stackless.tasklet(ClientTasklet)(client, server, clientSocket) - stackless.run() - - print "Done" Modified: stackless/sandbox/examples/scheduleAlternative.py ============================================================================== --- stackless/sandbox/examples/scheduleAlternative.py (original) +++ stackless/sandbox/examples/scheduleAlternative.py Sat Mar 24 10:43:31 2007 @@ -1,114 +1,17 @@ # -# The alternative approach to scheduling. +# Hi, # -# Author: Richard Tew +# These examples and libraries are no longer maintained here. The versions +# you find here, are possibly old and lack recent fixes. # -# This code was written to serve as an example of Stackless Python usage. -# Feel free to email me with any questions, comments, or suggestions for -# improvement. +# The new versions can be found here: +# +# http://code.google.com/p/stacklessexamples/wiki/StacklessExamples +# +# Please feel free to email the Stackless mailing list: +# +# http://www.stackless.com/mailman/listinfo/stackless +# +# Thanks, +# Richard Tew. # -# Benefits of this approach: -# -# - It lends itself well to embedding, if implemented in C or C++. -# -# - It allows more precise control. -# -# Limitations of this approach: -# -# - The expectation is that the scheduler will be empty because of this -# will exit pretty much immediately. So anything which calls to -# 'stackless.schedule' rather than using 'BeNice' or 'Sleep' will -# break this scheduling model and prevent it from working as -# expected. After all, if there are tasklets in the scheduler it -# continues to run and does not exit. -# -# Ideally 'stackless.schedule' should be patched to call BeNice. Or -# calls to it just avoided completely. -# - -import time -import stackless - -yieldChannel = stackless.channel() -sleepingTasklets = [] - -# Utility functions for tasklets to call. - -def BeNice(): - """ Signal that the tasklet can be interrupted. """ - yieldChannel.receive() - -def Sleep(secondsToWait): - """ Put the current tasklet to sleep for a number of seconds. """ - channel = stackless.channel() - endTime = time.time() + secondsToWait - sleepingTasklets.append((endTime, channel)) - sleepingTasklets.sort() - # Block until we get sent an awakening notification. - channel.receive() - -# Scheduler running related functions. - -def CheckSleepingTasklets(): - """ Awaken all tasklets which are due to be awakened. """ - while len(sleepingTasklets): - endTime = sleepingTasklets[0][0] - if endTime > time.time(): - break - channel = sleepingTasklets[0][1] - del sleepingTasklets[0] - # We have to send something, but it doesn't matter what as it is not used. - channel.send(None) - -def ScheduleTasklets(): - # Only schedule as many tasklets as there are waiting when - # we start. This is because some of the tasklets we awaken - # may BeNice their way back onto the channel. Well they - # would - n = -yieldChannel.balance - while n > 0: - yieldChannel.send(None) - n -= 1 - - CheckSleepingTasklets() - - # Run any tasklets which need to be scheduled. As long as the BeNice and - # Sleep callers do not use schedule they should never be in the scheduler - # at this point, but rather back in the yield channel or on a sleep channel. - # Loosely guessing, I would say that only newly created tasklets should - # ever be in the scheduler. And nothing should stay in there for that - # long before moving out by using Sleep or BeNice. If something does stay - # in there too long then it is not yielding or is keeping the scheduler - # running by using 'stackless.schedule' which is not compatible with the - # way this method intends the scheduler to be used. - - interruptedTasklet = stackless.run(1000000) - if interruptedTasklet: - # Should really print a stacktrace from the tasklet so it can be - # rewritten to 'be nice'. Alternatively the tasklet could be killed - # at this point if that suits the application. - interruptedTasklet.insert() - -exitScheduler = False - -def Run(): - def Test(n): - global exitScheduler - while n: - if n % 2 == 1: - print n, "BeNice" - BeNice() - else: - print n, "Sleep" - Sleep(1.0) - n -= 1 - exitScheduler = True - - # Do 10 iterations. - stackless.tasklet(Test)(10) - - while not exitScheduler: - ScheduleTasklets() - -if __name__ == '__main__': - Run() Modified: stackless/sandbox/examples/scheduleNormal.py ============================================================================== --- stackless/sandbox/examples/scheduleNormal.py (original) +++ stackless/sandbox/examples/scheduleNormal.py Sat Mar 24 10:43:31 2007 @@ -1,74 +1,17 @@ # -# The normal approach to scheduling. +# Hi, # -# Author: Richard Tew +# These examples and libraries are no longer maintained here. The versions +# you find here, are possibly old and lack recent fixes. # -# This code was written to serve as an example of Stackless Python usage. -# Feel free to email me with any questions, comments, or suggestions for -# improvement. +# The new versions can be found here: +# +# http://code.google.com/p/stacklessexamples/wiki/StacklessExamples +# +# Please feel free to email the Stackless mailing list: +# +# http://www.stackless.com/mailman/listinfo/stackless +# +# Thanks, +# Richard Tew. # -# Benefits of this approach: -# -# - It is easy to use from the interpreter. -# -# Limitations of this approach: -# -# - If there are no tasklets that run for the life of the application -# or script then the scheduler may exit when things are not complete. -# One example of this is when all tasklets which were in the -# scheduler and did not complete are waiting on channels. -# - -import time -import stackless - -exitScheduler = False - -sleepingTasklets = [] - -# Utility functions for tasklets to call. - -def Sleep(secondsToWait): - """ Put the current tasklet to sleep for a number of seconds. """ - channel = stackless.channel() - endTime = time.time() + secondsToWait - sleepingTasklets.append((endTime, channel)) - sleepingTasklets.sort() - # Block until we get sent an awakening notification. - channel.receive() - -# Scheduler running related functions. - -def ManageSleepingTasklets(): - """ Awaken all tasklets which are due to be awakened. """ - while not exitScheduler: - while len(sleepingTasklets): - endTime = sleepingTasklets[0][0] - if endTime > time.time(): - break - channel = sleepingTasklets[0][1] - del sleepingTasklets[0] - # It does not matter what we send as it is not used. - channel.send(None) - stackless.schedule() - - -def Run(): - def Test(n): - global exitScheduler - while n: - print n, "Sleep" - Sleep(1.0) - n -= 1 - exitScheduler = True - - stackless.tasklet(Test)(10) - stackless.tasklet(ManageSleepingTasklets)() - - # This will run until there are no scheduled tasklets. But because we - # create one to manage the sleeping tasklets this will mean it will run - # indefinitely. - stackless.run() - -if __name__ == '__main__': - Run() Modified: stackless/sandbox/examples/stacklesssocket.py ============================================================================== --- stackless/sandbox/examples/stacklesssocket.py (original) +++ stackless/sandbox/examples/stacklesssocket.py Sat Mar 24 10:43:31 2007 @@ -1,440 +1,17 @@ # -# Stackless compatible socket module: +# Hi, # -# Author: Richard Tew +# These examples and libraries are no longer maintained here. The versions +# you find here, are possibly old and lack recent fixes. # -# This code was written to serve as an example of Stackless Python usage. -# Feel free to email me with any questions, comments, or suggestions for -# improvement. +# The new versions can be found here: +# +# http://code.google.com/p/stacklessexamples/wiki/StacklessExamples +# +# Please feel free to email the Stackless mailing list: +# +# http://www.stackless.com/mailman/listinfo/stackless +# +# Thanks, +# Richard Tew. # -# This wraps the asyncore module and the dispatcher class it provides in order -# write a socket module replacement that uses channels to allow calls to it to -# block until a delayed event occurs. -# -# Not all aspects of the socket module are provided by this file. Examples of -# it in use can be seen at the bottom of this file. -# -# NOTE: Versions of the asyncore module from Python 2.4 or later include bug -# fixes and earlier versions will not guarantee correct behaviour. -# Specifically, it monitors for errors on sockets where the version in -# Python 2.3.3 does not. -# - -# Possible improvements: -# - More correct error handling. When there is an error on a socket found by -# poll, there is no idea what it actually is. -# - Launching each bit of incoming data in its own tasklet on the recvChannel -# send is a little over the top. It should be possible to add it to the -# rest of the queued data - -import stackless -import asyncore -import socket as stdsocket # We need the "socket" name for the function we export. - -# If we are to masquerade as the socket module, we need to provide the constants. -for k, v in stdsocket.__dict__.iteritems(): - if k.upper() == k: - globals()[k] = v -error = stdsocket.error -timeout = stdsocket.timeout - -# urllib2 apparently uses this directly. We need to cater for that. -_fileobject = stdsocket._fileobject - -# WARNING: this function blocks and is not thread safe. -# The only solution is to spawn a thread to handle all -# getaddrinfo requests. Implementing a stackless DNS -# lookup service is only second best as getaddrinfo may -# use other methods. -getaddrinfo = stdsocket.getaddrinfo - - -managerRunning = False - -def ManageSockets(): - global managerRunning - - while len(asyncore.socket_map): - # Check the sockets for activity. - asyncore.poll(0.05) - # Yield to give other tasklets a chance to be scheduled. - stackless.schedule() - - managerRunning = False - -def socket(family=AF_INET, type=SOCK_STREAM, proto=0): - global managerRunning - - currentSocket = stdsocket.socket(family, type, proto) - ret = stacklesssocket(currentSocket) - # Ensure that the sockets actually work. - if not managerRunning: - managerRunning = True - stackless.tasklet(ManageSockets)() - return ret - -# This is a facade to the dispatcher object. -# It exists because asyncore's socket map keeps a bound reference to -# the dispatcher and hence the dispatcher will never get gc'ed. -# -# The rest of the world sees a 'stacklesssocket' which has no cycles -# and will be gc'ed correctly - -class stacklesssocket(object): - def __init__(self, sock): - self.sock = sock - self.dispatcher = dispatcher(sock) - - def __getattr__(self, name): - # Forward nearly everything to the dispatcher - if not name.startswith("__"): - # I don't like forwarding __repr__ - return getattr(self.dispatcher, name) - - def __setattr__(self, name, value): - if name == "wrap_accept_socket": - # We need to pass setting of this to the dispatcher. - self.dispatcher.wrap_accept_socket = value - else: - # Anything else gets set locally. - object.__setattr__(self, name, value) - - def __del__(self): - # Close dispatcher if it isn't already closed - if self.dispatcher._fileno is not None: - try: - self.dispatcher.close() - finally: - self.dispatcher = None - - # Catch this one here to make gc work correctly. - # (Consider if stacklesssocket gets gc'ed before the _fileobject) - def makefile(self, mode='r', bufsize=-1): - return stdsocket._fileobject(self, mode, bufsize) - - -class dispatcher(asyncore.dispatcher): - connectChannel = None - acceptChannel = None - recvChannel = None - - def __init__(self, sock): - # This is worth doing. I was passing in an invalid socket which was - # an instance of dispatcher and it was causing tasklet death. - if not isinstance(sock, stdsocket.socket): - raise StandardError("Invalid socket passed to dispatcher") - asyncore.dispatcher.__init__(self, sock) - - # if self.socket.type == SOCK_DGRAM: - # self.dgramRecvChannels = {} - # self.dgramReadBuffers = {} - #else: - self.recvChannel = stackless.channel() - self.readBuffer = None - - self.sendBuffer = '' - self.sendToBuffers = [] - - def writable(self): - if self.socket.type != SOCK_DGRAM and not self.connected: - return True - return len(self.sendBuffer) or len(self.sendToBuffers) - - def accept(self): - if not self.acceptChannel: - self.acceptChannel = stackless.channel() - return self.acceptChannel.receive() - - def connect(self, address): - asyncore.dispatcher.connect(self, address) - # UDP sockets do not connect. - if self.socket.type != SOCK_DGRAM and not self.connected: - if not self.connectChannel: - self.connectChannel = stackless.channel() - self.connectChannel.receive() - - def send(self, data): - self.sendBuffer += data - stackless.schedule() - return len(data) - - def sendall(self, data): - # WARNING: this will busy wait until all data is sent - # It should be possible to do away with the busy wait with - # the use of a channel. - self.sendBuffer += data - while self.sendBuffer: - stackless.schedule() - return len(data) - - def sendto(self, sendData, sendAddress): - waitChannel = None - for idx, (data, address, channel, sentBytes) in enumerate(self.sendToBuffers): - if address == sendAddress: - self.sendToBuffers[idx] = (data + sendData, address, channel, sentBytes) - waitChannel = channel - break - if waitChannel is None: - waitChannel = stackless.channel() - self.sendToBuffers.append((sendData, sendAddress, waitChannel, 0)) - return waitChannel.receive() - - # Read at most byteCount bytes. - def recv(self, byteCount): - if self.readBuffer is None: - self.readBuffer = "" - if len(self.readBuffer) < byteCount: - self.readBuffer += self.recvChannel.receive() - stackless.schedule() - ret = self.readBuffer[:byteCount] - self.readBuffer = self.readBuffer[byteCount:] - return ret - - def recvfrom(self, byteCount): - if self.readBuffer is None: - self.readBuffer = [] - - ret = "" - address = None - while 1: - while len(self.readBuffer): - data, dataAddress = self.readBuffer[0] - if address is None: - address = dataAddress - elif address != dataAddress: - # They got all the sequenial data from the given address. - return ret, address - - ret += data - if len(ret) >= byteCount: - # We only partially used up this data. - self.readBuffer[0] = ret[byteCount:], address - return ret[:byteCount], address - - # We completely used up this data. - del self.readBuffer[0] - - self.readBuffer.append(self.recvChannel.receive()) - - def close(self): - asyncore.dispatcher.close(self) - self.connected = False - self.accepting = False - self.sendBuffer = None # breaks the loop in sendall - - # Clear out all the channels with relevant errors. - while self.acceptChannel and self.acceptChannel.balance < 0: - self.acceptChannel.send_exception(error, 9, 'Bad file descriptor') - while self.connectChannel and self.connectChannel.balance < 0: - self.connectChannel.send_exception(error, 10061, 'Connection refused') - while self.recvChannel and self.recvChannel.balance < 0: - self.recvChannel.send_exception(error, 10054, 'Connection reset by peer') - - # asyncore doesn't support this. Why not? - def fileno(self): - return self.socket.fileno() - - def handle_accept(self): - if self.acceptChannel and self.acceptChannel.balance < 0: - currentSocket, clientAddress = asyncore.dispatcher.accept(self) - currentSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) - # Give them the asyncore based socket, not the standard one. - currentSocket = self.wrap_accept_socket(currentSocket) - stackless.tasklet(self.acceptChannel.send)((currentSocket, clientAddress)) - - # Inform the blocked connect call that the connection has been made. - def handle_connect(self): - if self.socket.type != SOCK_DGRAM: - if not self.connectChannel: - self.connectChannel = stackless.channel() - self.connectChannel.send(None) - - # Asyncore says its done but self.readBuffer may be non-empty - # so can't close yet. Do nothing and let 'recv' trigger the close. - def handle_close(self): - pass - - # Some error, just close the channel and let that raise errors to - # blocked calls. - def handle_expt(self): - self.close() - - def handle_read(self): - try: - if self.socket.type == SOCK_DGRAM: - ret, address = self.socket.recvfrom(20000) - stackless.tasklet(self.recvChannel.send)((ret, address)) - else: - ret = asyncore.dispatcher.recv(self, 20000) - stackless.tasklet(self.recvChannel.send)(ret) - except stdsocket.error, err: - # XXX Is this correct? - # If there's a read error assume the connection is - # broken and drop any pending output - if self.sendBuffer: - self.sendBuffer = "" - # Why can't I pass the 'err' by itself? - self.recvChannel.send_exception(stdsocket.error, err) - - def handle_write(self): - if len(self.sendBuffer): - sentBytes = asyncore.dispatcher.send(self, self.sendBuffer[:512]) - self.sendBuffer = self.sendBuffer[sentBytes:] - elif len(self.sendToBuffers): - data, address, channel, oldSentBytes = self.sendToBuffers[0] - sentBytes = self.socket.sendto(data, address) - totalSentBytes = oldSentBytes + sentBytes - if len(data) > sentBytes: - self.sendToBuffers[0] = data[sentBytes:], address, channel, totalSentBytes - else: - del self.sendToBuffers[0] - stackless.tasklet(channel.send)(totalSentBytes) - - # In order for incoming connections to be stackless compatible, - # they need to be wrapped by an asyncore based dispatcher subclass. - def wrap_accept_socket(self, currentSocket): - return stacklesssocket(currentSocket) - - -if __name__ == '__main__': - import struct - # Test code goes here. - testAddress = "127.0.0.1", 3000 - info = -12345678 - data = struct.pack("i", info) - dataLength = len(data) - - print "creating listen socket" - def TestTCPServer(address): - global info, data, dataLength - - listenSocket = socket(AF_INET, SOCK_STREAM) - listenSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) - listenSocket.bind(address) - listenSocket.listen(5) - - NUM_TESTS = 2 - - i = 1 - while i < NUM_TESTS + 1: - # No need to schedule this tasklet as the accept should yield most - # of the time on the underlying channel. - print "waiting for connection test", i - currentSocket, clientAddress = listenSocket.accept() - print "received connection", i, "from", clientAddress - - if i == 1: - currentSocket.close() - elif i == 2: - print "server test", i, "send" - currentSocket.send(data) - print "server test", i, "recv" - if currentSocket.recv(4) != "": - print "server recv(1)", i, "FAIL" - break - # multiple empty recvs are fine - if currentSocket.recv(4) != "": - print "server recv(2)", i, "FAIL" - break - else: - currentSocket.close() - - print "server test", i, "OK" - i += 1 - - if i != NUM_TESTS+1: - print "server: FAIL", i - else: - print "server: OK", i - - print "Done server" - - def TestTCPClient(address): - global info, data, dataLength - - # Attempt 1: - clientSocket = socket() - clientSocket.connect(address) - print "client connection", 1, "waiting to recv" - if clientSocket.recv(5) != "": - print "client test", 1, "FAIL" - else: - print "client test", 1, "OK" - - # Attempt 2: - clientSocket = socket() - clientSocket.connect(address) - print "client connection", 2, "waiting to recv" - s = clientSocket.recv(dataLength) - t = struct.unpack("i", s) - if t[0] == info: - print "client test", 2, "OK" - else: - print "client test", 2, "FAIL" - - def TestMonkeyPatchUrllib(uri): - # replace the system socket with this module - import sys - oldSocket = sys.modules["socket"] - sys.modules["socket"] = __import__(__name__) - try: - import urllib # must occur after monkey-patching! - f = urllib.urlopen(uri) - if not isinstance(f.fp._sock, stacklesssocket): - raise AssertionError("failed to apply monkeypatch") - s = f.read() - if len(s) != 0: - print "Fetched", len(s), "bytes via replaced urllib" - else: - raise AssertionError("no text received?") - finally: - sys.modules["socket"] = oldSocket - - def TestMonkeyPatchUDP(address): - # replace the system socket with this module - import sys - oldSocket = sys.modules["socket"] - sys.modules["socket"] = __import__(__name__) - try: - def UDPServer(address): - listenSocket = socket(AF_INET, SOCK_DGRAM) - listenSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) - listenSocket.bind(address) - - i = 1 - cnt = 0 - while 1: - #print "waiting for connection test", i - #currentSocket, clientAddress = listenSocket.accept() - #print "received connection", i, "from", clientAddress - - print "waiting to receive" - t = listenSocket.recvfrom(256) - cnt += len(t[0]) - print "received", t[0], cnt - if cnt == 512: - break - - def UDPClient(address): - clientSocket = socket(AF_INET, SOCK_DGRAM) - # clientSocket.connect(address) - print "sending 512 byte packet" - sentBytes = clientSocket.sendto("-"+ ("*" * 510) +"-", address) - print "sent 512 byte packet", sentBytes - - stackless.tasklet(UDPServer)(address) - stackless.tasklet(UDPClient)(address) - stackless.run() - finally: - sys.modules["socket"] = oldSocket - - stackless.tasklet(TestTCPServer)(testAddress) - stackless.tasklet(TestTCPClient)(testAddress) - stackless.run() - - stackless.tasklet(TestMonkeyPatchUrllib)("http://python.org/") - stackless.run() - - TestMonkeyPatchUDP(testAddress) - - print "result: SUCCESS" Modified: stackless/sandbox/examples/threadchannels.py ============================================================================== --- stackless/sandbox/examples/threadchannels.py (original) +++ stackless/sandbox/examples/threadchannels.py Sat Mar 24 10:43:31 2007 @@ -1,125 +1,17 @@ # -# A demonstration of how channels are allow interthread communication. +# Hi, # -# Author: Richard Tew +# These examples and libraries are no longer maintained here. The versions +# you find here, are possibly old and lack recent fixes. # -# This code was written to serve as an example of Stackless Python usage. -# Feel free to email me with any questions, comments, or suggestions for -# improvement. +# The new versions can be found here: +# +# http://code.google.com/p/stacklessexamples/wiki/StacklessExamples +# +# Please feel free to email the Stackless mailing list: +# +# http://www.stackless.com/mailman/listinfo/stackless +# +# Thanks, +# Richard Tew. # -# FURTHER DETAIL: -# -# Sending or receiving on a channel when there is a waiting tasklet -# from another thread, will always block and schedule the tasklet -# on the other thread. The channel 'preference' attribute has no -# effect on this behaviour. This may not be the most optimal way -# to do sleeping and it might be better to have per-thread -# management of sleepers. -# - -import threading -import stackless -import time - -# Flag which should allow the threads to exit if cleared. -running = True - -# Altered boilerplate Sleep function. -sleepingTasklets = [] -sleepCountByThread = {} -threadIDByChannelID = {} -lock = threading.Lock() - -def GetThreadID(): - return id(threading.currentThread()) - -def Sleep(secondsToWait): - global sleepingTasklets, lock, threadIDByChannelID, sleepCountByThread - - channel = stackless.channel() - endTime = time.time() + secondsToWait - threadID = GetThreadID() - - lock.acquire(True) - sleepCountByThread[threadID] = sleepCountByThread.get(threadID, 0) + 1 - threadIDByChannelID[id(channel)] = threadID - sleepingTasklets.append((endTime, channel)) - sleepingTasklets.sort() - lock.release() - - # Block until we get sent an awakening notification. - channel.receive() - -def ManageSleepingTasklets(threadID): - global sleepingTasklets, lock, running, threadIDByChannelID, sleepCountByThread - - sleepingTasklets = [] - while running: - if len(sleepingTasklets): - lock.acquire(True) - endTime = sleepingTasklets[0][0] - if endTime <= time.time(): - channel = sleepingTasklets[0][1] - del sleepingTasklets[0] - threadID = threadIDByChannelID[id(channel)] - sleepCountByThread[threadID] -= 1 - lock.release() - - # We have to send something, but it doesn't matter what as it is not used. - channel.send(None) - else: - lock.release() - elif stackless.getruncount() == 1: - # Give up if there are no more sleeping tasklets. Otherwise the two - # threads keep on running endlessly. - print "Sleeping tasklet exited due to no remaining work." - break - stackless.schedule() - else: - print threadID, "Sleeping tasklet exited due to change in 'running' flag" - -# ... - -def looping_tasklet(threadID, taskletID): - n = 3 - while n > 0: - n -= 1 - print threadID, "looping_tasklet", taskletID, "loop", n - Sleep(1.0) - print threadID, "looping_tasklet", taskletID, "exit" - - -def a_main_tasklet(): - global running - - threadID = GetThreadID() - - for i in range(3): - stackless.tasklet(looping_tasklet)(threadID, i+1) - - # We need to catch the keyboard interrupt and signal the other thread to exit. - try: - print threadID, "start: runcount", stackless.getruncount() - - # Do a preliminary run to get some tasklets in the scheduler or some - # sleeping tasklets in place, otherwise we would not run at all. - stackless.run() - - # Now we should be set to run until we are done. - while running and (stackless.getruncount() > 1 or sleepCountByThread.get(threadID, 0)): - print threadID, "start: runcount", stackless.getruncount(), "sleepcount", sleepCountByThread.get(threadID, 0) - stackless.run() - print threadID, "stop: runcount", stackless.getruncount(), "sleepcount", sleepCountByThread.get(threadID, 0) - except: - running = False - raise - -if __name__ == "__main__": - threadID = GetThreadID() - - stackless.tasklet(ManageSleepingTasklets)(threadID) - - thread = threading.Thread(target=a_main_tasklet) - thread.start() - - a_main_tasklet() Modified: stackless/sandbox/examples/threadscheduling.py ============================================================================== --- stackless/sandbox/examples/threadscheduling.py (original) +++ stackless/sandbox/examples/threadscheduling.py Sat Mar 24 10:43:31 2007 @@ -1,100 +1,17 @@ # -# A demonstration of how each thread has its own scheduler. +# Hi, # -# Author: Richard Tew +# These examples and libraries are no longer maintained here. The versions +# you find here, are possibly old and lack recent fixes. # -# This code was written to serve as an example of Stackless Python usage. -# Feel free to email me with any questions, comments, or suggestions for -# improvement. +# The new versions can be found here: +# +# http://code.google.com/p/stacklessexamples/wiki/StacklessExamples +# +# Please feel free to email the Stackless mailing list: +# +# http://www.stackless.com/mailman/listinfo/stackless +# +# Thanks, +# Richard Tew. # -# FURTHER DETAIL: -# -# This example starts some tasklets on the main thread, and starts a second -# thread as well, starting some tasklets on that. You should be able to -# see that the scheduler on each thread is unrelated to the one on the -# other, which is why I need to start a ManageSleepingTasklets for each of -# them. -# -# POSSIBLE PROBLEMS: -# -# If Stackless complains that "run() must be run from the main thread's -# main tasklet", then you need to get a later version of Stackless. -# This constraint was removed. -# - -import threading -import stackless -import time - -_locals = threading.local() -running = True - -# Altered boilerplate Sleep function. - -def Sleep(secondsToWait): - channel = stackless.channel() - endTime = time.time() + secondsToWait - _locals.sleepingTasklets.append((endTime, channel)) - _locals.sleepingTasklets.sort() - # Block until we get sent an awakening notification. - channel.receive() - -def ManageSleepingTasklets(threadID): - global running - - _locals.sleepingTasklets = [] - while running: - if len(_locals.sleepingTasklets): - endTime = _locals.sleepingTasklets[0][0] - if endTime <= time.time(): - channel = _locals.sleepingTasklets[0][1] - del _locals.sleepingTasklets[0] - # We have to send something, but it doesn't matter what as it is not used. - channel.send(None) - elif stackless.getruncount() == 1: - # Give up if there are no more sleeping tasklets. Otherwise the two - # threads keep on running endlessly. - break - stackless.schedule() - -# ... - -def looping_tasklet(threadID, taskletID): - n = 3 - while n > 0: - n -= 1 - print threadID, "looping_tasklet", taskletID, "loop", n - Sleep(1.0) - print threadID, "looping_tasklet", taskletID, "exit" - - -def a_main_tasklet(): - threadID = 2 - - stackless.tasklet(ManageSleepingTasklets)(threadID) - - stackless.tasklet(looping_tasklet)(threadID, 1) - - print threadID, "runcount.1", stackless.getruncount() - stackless.run() - -if __name__ == "__main__": - global running - - threadID = 1 - - stackless.tasklet(ManageSleepingTasklets)(threadID) - - stackless.tasklet(looping_tasklet)(threadID, 1) - stackless.tasklet(looping_tasklet)(threadID, 2) - - print threadID, "runcount", stackless.getruncount() - - thread = threading.Thread(target=a_main_tasklet) - thread.start() - - try: - stackless.run() - except: - running = False - raise Modified: stackless/sandbox/examples/twisted/twisted_timer.py ============================================================================== --- stackless/sandbox/examples/twisted/twisted_timer.py (original) +++ stackless/sandbox/examples/twisted/twisted_timer.py Sat Mar 24 10:43:31 2007 @@ -1,76 +1,17 @@ -# Twisted and Stackless - example 1 # -# In this example, most of the time is spent in the twisted event loop. This -# approach allows you to control the granularity of tasklet execution based on -# time. At 30fps, a timer executes that schedules stackless tasklets to run - a -# simple tasklet just prints "do-op". +# Hi, # -# by Greg Hazel +# These examples and libraries are no longer maintained here. The versions +# you find here, are possibly old and lack recent fixes. # -# If you have any questions related to this example: +# The new versions can be found here: +# +# http://code.google.com/p/stacklessexamples/wiki/StacklessExamples +# +# Please feel free to email the Stackless mailing list: +# +# http://www.stackless.com/mailman/listinfo/stackless +# +# Thanks, +# Richard Tew. # -# - If they are related to how Twisted works, please contact the -# Twisted mailing list: -# -# http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python -# -# - If they are related to how Stackless works, please contact -# the Stackless mailing list: -# -# http://www.tismer.com/mailman/listinfo/stackless -# -# Otherwise if they are related to how Twisted works in conjunction with -# Stackless, please contact the Stackless mailing list: -# -# http://www.tismer.com/mailman/listinfo/stackless - -import time -import stackless -from twisted.internet import task, reactor - -# a few globals for fun -ideal_fps = 30.0 -fps = 0 -clock = getattr(time, 'clock', time.time) -last_time = clock() - - -def frame(): - global fps, last_time - - # a silly fps counter - this_time = clock() - d = 1.0 / (this_time - last_time) - fps = (fps + d) / 2.0 - last_time = this_time - print fps - - # allow tasklets to run - stackless.schedule() - -# start the timer -t = task.LoopingCall(frame) -t.start(1.0/ideal_fps) - - -def tasklet(): - - while True: - # complicated operation with side-effects - print 'do-op' - - # allow the reactor to resume - stackless.schedule() - - # don't loop forever - if not reactor.running: - break - - -# start the simple tasklet -stackless.tasklet(tasklet)() - -# start the reactor -stackless.tasklet(reactor.run)() -# start the stackless scheduler -stackless.run() Modified: stackless/sandbox/examples/twisted/twisted_webserver.py ============================================================================== --- stackless/sandbox/examples/twisted/twisted_webserver.py (original) +++ stackless/sandbox/examples/twisted/twisted_webserver.py Sat Mar 24 10:43:31 2007 @@ -1,111 +1,17 @@ -#!/usr/bin/env python -""" -Webserver.py -Andrew Francis -March 1st, 2007 - -Example of Twisted and Stackless integration that -blocks. - -The server listens on http://localhost:8000 - -The programme is fine for many purposes. However there is a -flaw. Whenever the server tasklet blocks, it blocks the entire -programme. Ideally other tasklets, such as the Tick tasklet should -run while the server tasklet waits for connections. -""" - -# If you have any questions related to this example: # -# - If they are related to how Twisted works, please contact the -# Twisted mailing list: +# Hi, # -# http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python +# These examples and libraries are no longer maintained here. The versions +# you find here, are possibly old and lack recent fixes. # -# - If they are related to how Stackless works, please contact -# the Stackless mailing list: +# The new versions can be found here: +# +# http://code.google.com/p/stacklessexamples/wiki/StacklessExamples +# +# Please feel free to email the Stackless mailing list: +# +# http://www.stackless.com/mailman/listinfo/stackless +# +# Thanks, +# Richard Tew. # -# http://www.tismer.com/mailman/listinfo/stackless -# -# Otherwise if they are related to how Twisted works in conjunction with -# Stackless, please contact the Stackless mailing list: -# -# http://www.tismer.com/mailman/listinfo/stackless - -import time -import stackless -from twisted.web import http - -class Server(object): - - def execute(self, port, requestChannel): - MyRequestHandler.requestChannel = requestChannel - reactor.listenTCP(port, MyHttpFactory()) - reactor.run() - - -class Cgi(object): - def __init__(self, name, channel): - self.name = name - self.channel = channel - self.count = 0 - return - - def execute(self): - while (1): - - replyChannel = self.channel.receive() - replyChannel.send("" + \ - self.name + "count :" + str(self.count) + \ - "") - - self.count = self.count + 1 - stackless.schedule() - - -def tick(): - count = 0 - while (1): - print "tick: ", count - count += 1 - stackless.schedule() - - - -class MyRequestHandler(http.Request): - - def process(self): - """ - send back a unique channel that identifies the request handler - """ - replyChannel = stackless.channel() - MyRequestHandler.requestChannel.send(replyChannel) - result = replyChannel.receive() - self.write(result) - self.finish() - - -class MyHttp(http.HTTPChannel): - requestFactory = MyRequestHandler - - -class MyHttpFactory(http.HTTPFactory): - protocol = MyHttp - - -if __name__ == "__main__": - from twisted.internet import reactor - - channel = stackless.channel() - - cgiTasklet = Cgi("cgiTasklet-1", channel) - server = Server() - - stackless.tasklet(cgiTasklet.execute)() - stackless.tasklet(server.execute)(8000, channel) - print "Web Server started" - stackless.tasklet(tick)() - - print "entering main loop" - while (stackless.getruncount() > 1): - stackless.schedule() \ No newline at end of file Modified: stackless/sandbox/examples/twisted/twisted_webserver_threaded.py ============================================================================== --- stackless/sandbox/examples/twisted/twisted_webserver_threaded.py (original) +++ stackless/sandbox/examples/twisted/twisted_webserver_threaded.py Sat Mar 24 10:43:31 2007 @@ -1,127 +1,17 @@ -#!/usr/bin/env python -""" -ThreadedWebserver.py -Andrew Francis -March 1st, 2007 - -Example of Twisted and Stackless integration that allows non-blocking -tasklets to execute - -The server listens on http://localhost:8000 - -Unlike the previous example, ThreadedWebserver runs Stackless in a -separate thread. While Twisted is blocked waiting for connections, -the tick tasklet (or any other tasklet) can execute. - -As per Carlos's de Paula's observation, a time.sleep is included to -increase performance. I suspect the Global interpreter lock is playing -a role. On my machine time.sleep(.01) is fine. at .001, the server will -fail after multiple uses. -""" - -# If you have any questions related to this example: # -# - If they are related to how Twisted works, please contact the -# Twisted ma