Bernat Romagosa
Bernat Romagosa

Reputation: 1202

Defining a maximum running time for a process

I need to stop a process from running longer than n seconds, so here's what I thought I'd do:

|aProcess|
aProcess := [ 10000 timesRepeat: [Transcript show: 'X'] ] fork.
[(Delay forSeconds: 1) wait. aProcess terminate] fork.

I thought this was the proper way to proceed, but it seems to fail from time to time, the Transcript just goes on printing Xes. What bugs me is that it does work sometimes and I can't figure out what the work/fail pattern is.

Upvotes: 3

Views: 246

Answers (2)

Ramon Leon
Ramon Leon

Reputation: 547

This is already in the library, you don't need to reinvent it.

[10000 timesRepeat: [Transcript show: 'X']] 
    valueWithin: 1 second onTimeout: [Transcript show: 'stop']

Upvotes: 4

Janko Mivšek
Janko Mivšek

Reputation: 3964

Both processes are running on the same priority, that's why the second process actually doesn't get chance to interrupt the first one at all. Try to run the first loop in lower priority or even better, second one in higher:

 [(Delay forSeconds: 1) wait. aProcess terminate] 
       forkAt: Processor userInterruptPriority

Upvotes: 4

Related Questions