- 论坛徽章:
- 5
|
小伙伴们, 试试: {:2_172:}
1: 2 元素并行运行 ( 2 Label )
2: #!/usr/bin/perl (test in linux)
- #!/usr/bin/perl
- use threads;
- use threads::shared;
- use Tkx;
- my ( $V1, $V2 ); # textvariable
- my ( $T1, $T2 ); # 2 threads
- my $R1 : shared = 'E 1:'; # $R1 ~> $V1, $R2 ~> $V2
- my $R2 : shared = 'E 2:';
- my $Go : shared = 0; # flag: exit
- my $push = 0; # flag: create thread
- my $milliseconds = 50; # time: update
- # window
- my $win = Tkx::widget->new(".");
- $win->g_wm_title("2 Threads");
- $win->g_wm_minsize( 200, 150 );
- my $content = $win->new_ttk__frame( -borderwidth => 50 );
- my $start = $content->new_ttk__button(
- -text => "start",
- -command => \&start
- );
- my $quit = $content->new_ttk__button(
- -text => "quit",
- -command => \&quit
- );
- Tkx::font_create(
- "BIG",
- -family => "Helvetica",
- -size => 16,
- -weight => "bold"
- );
- my $la1 = $content->new_ttk__label( -textvariable => \$V1, -font => 'BIG' );
- my $la2 = $content->new_ttk__label( -textvariable => \$V2, -font => 'BIG' );
- $content->g_pack( -anchor => 'nw', -padx => 5, -pady => 5 );
- $la1->g_pack( -anchor => 'nw', -padx => 5, -pady => 0 );
- $la2->g_pack( -anchor => 'nw', -padx => 5, -pady => 50 );
- $start->g_pack( -anchor => 'nw', -padx => 5, -pady => 2 );
- $quit->g_pack( -anchor => 'nw', -padx => 5, -pady => 2 );
- # subs
- sub Sleep { select undef, undef, undef, shift; }
- sub update { ( $V1, $V2 ) = ( $R1, $R2 ) }
- sub repeat {
- my ( $ms, $sub, $update ) = @_;
- $update = sub { $sub->(); Tkx::after( $ms, $update ); };
- Tkx::after( $ms, $update );
- }
- sub start {
- return if $push++;
- #print "hello world\n";
- $T1 = threads->create( \&Work1 );
- $T2 = threads->create( \&Work2 );
- }
- sub quit {
- my $running = threads->list;
- exit if $running < 1;
- $Go = 1;
- $T1->join;
- $T2->join;
- exit;
- }
- # threads
- sub Work1 {
- for my $i ( 0 .. 150 ) {
- return if $Go;
- $R1 = "E 1: $i";
- Sleep 0.1;
- }
- $R1 = 'End work1';
- }
- sub Work2 {
- for my $i ( 0 .. 50 ) {
- return if $Go;
- $R2 = "E 2: $i";
- Sleep 0.3;
- }
- $R2 = 'End work2';
- }
- # main
- repeat $milliseconds, \&update;
- Tkx::MainLoop();
复制代码 |
|