samedi 1 avril 2023

Singleton pattern for multi-processing on Pharo 10.0 ( Smalltalk )

I can't pass the test below.

"SingletonTest"
testCurrent
        
    | semaphore object1 object2 |
    Singleton initialize.

    semaphore := Semaphore new.

    [ 
    Processor yield.
    object1 := Singleton initialize current.
    semaphore signal ] fork.

    object2 := Singleton initialize current.

    semaphore wait.
    self assert: object1 identicalTo: object2

Here is the implementation which is failed.

"Singleton class"
current

    current := current ifNil: [ 
                   (Delay forSeconds: 2) wait.
                   self new ].
    ^ current

I have tried to pass the test by using a naive exclusion control but the result was same.

"Singleton class"
current

    [ isProcessing ] whileTrue: [  ].
    isProcessing := true.
    current := current ifNil: [ 
                   (Delay forSeconds: 2) wait.
                   self new ].
    isProcessing := false.
    ^ current

How can I pass the test? I'm looking forward to hearing your tips!

Aucun commentaire:

Enregistrer un commentaire