1Wx::Thread(3) User Contributed Perl Documentation Wx::Thread(3)
2
3
4
6 Thread - using wxPerl with threads
7
9 # the order of these use()s is important
10 use threads;
11 use threads::shared;
12 use Wx;
13
14 my $DONE_EVENT : shared = Wx::NewEventType;
15
16 my $worker = threads->create( \&work );
17
18 # create frames, etc
19 my $frame = Wx::Frame->new( ... );
20 EVT_COMMAND( $frame, -1, $DONE_EVENT, \&done );
21 $app->MainLoop;
22
23 sub done {
24 my( $frame, $event ) = @_;
25
26 print $event->GetData;
27 }
28
29 sub work {
30 # ... do stuff, create a shared $result value
31
32 my $threvent = new Wx::PlThreadEvent( -1, $DONE_EVENT, $result );
33 Wx::PostEvent( $frame, $threvent );
34 }
35
36 # event handler
37 sub OnCreateThread {
38 # @_ = () is necessary to avoid "Scalars leaked"
39 my( $self, $event ) = @_; @_ = ();
40
41 threads->create( ... );
42 }
43
45 Threaded GUI application are somewhat different from non-GUI threaded
46 applications in that the main thread (which runs the GUI) must never
47 block. Also, in wxWidgets, no thread other than the main thread can
48 manipulate GUI objects. This leads to a hybrid model where worker
49 threads must send events to the main thread in order to change the GUI
50 state or signal their termination.
51
52 Order of module loading
53 It's necessary for "use Wx" to happen after <use threads::shared>.
54
55 Sending events from worker threads
56 "Wx::PlThreadEvent" can be used to communicate between worker and GUI
57 threads. The event can carry a shared value between threads.
58
59 my $DONE_EVENT : shared = Wx::NewEventType;
60
61 sub work {
62 # ... do some stuff
63 my $progress = new Wx::PlThreadEvent( -1, $DONE_EVENT, $progress );
64 Wx::PostEvent( $frame, $progress );
65
66 # ... do stuff, create a shared $result value
67 my $end = new Wx::PlThreadEvent( -1, $DONE_EVENT, $result );
68 Wx::PostEvent( $frame, $end );
69 }
70
71 The target of the event can be any "Wx::EvtHandler"
72
73 Receiving events from worker threads
74 "Wx::PlThreadEvent" is a command event and can be handled as such. The
75 "->GetData" method can be used to retrieve the shared data contained
76 inside the event.
77
78 my $DONE_EVENT : shared = Wx::NewEventType;
79
80 EVT_COMMAND( $frame, -1, $DONE_EVENT, \&done );
81
82 sub done {
83 my( $frame, $event ) = @_;
84
85 print $event->GetData;
86 }
87
88 Creating new threads
89 Creating new threads from event handlers works without problems except
90 from a little snag. In order not to trigger a bug in the Perl
91 interpreter, all event handler that directly or indirectly cause a
92 thread creation must clean @_ before starting the thread.
93
94 For example:
95
96 sub OnCreateThread {
97 my( $self, $event ) = @_; @_ = ();
98
99 threads->create( ... );
100 }
101
102 failure to do that will cause "scalars leaked" warnings from the Perl
103 interpreter.
104
105
106
107perl v5.32.1 2021-01-27 Wx::Thread(3)