|
| 1 | +function user %#codegen |
| 2 | + |
| 3 | + % we can print to stderr |
| 4 | + fprintf(2, 'hello world\n'); |
| 5 | + |
| 6 | + % we have access to command line arguments |
| 7 | + fprintf(2, 'got %d arguments\n', argc() ); |
| 8 | + for i=0:argc()-1 |
| 9 | + fprintf(2, ' arg %d: %s\n', i, argv(i)); |
| 10 | + end |
| 11 | + |
| 12 | + % we can send timestamped messages to the log |
| 13 | + % - no need to put a new line on the end |
| 14 | + stllog('hello world'); |
| 15 | + |
| 16 | + % note that if we send a string argument we need to convert it to a |
| 17 | + % C string |
| 18 | + stllog('%s', cstring('hello world')); |
| 19 | + |
| 20 | + % now we can launch a couple of threads, see thread1.m and thread2.m |
| 21 | + % launching returns a thread id, a small integer |
| 22 | + t1 = launch('thread1', 24) % pass a value to this thread |
| 23 | + stllog('thread id %d', t1) |
| 24 | + t2 = launch('thread2') |
| 25 | + stllog('thread id %d', t2) |
| 26 | + |
| 27 | + join(t1); % wait for thread 1 to finish |
| 28 | + sleep(5); |
| 29 | + cancel(t2); % kill thread 2 and wait for it |
| 30 | + join(t2) |
| 31 | + |
| 32 | + sleep(2) |
| 33 | + |
| 34 | + % create a semaphore |
| 35 | + s1 = newsemaphore('sem1'); |
| 36 | + stllog('sem id %d', s1); |
| 37 | + sleep(1) |
| 38 | + |
| 39 | + % launch a new thread, see thread3.m |
| 40 | + % it just waits for the semaphore, then prints a message |
| 41 | + t3 = launch('thread3', 42); |
| 42 | + stllog('thread id %d', t3); |
| 43 | + |
| 44 | + sleep(2); |
| 45 | + sempost(0); % wake up thread 3 |
| 46 | + sleep(1); |
| 47 | + sempost(0); % wake up thread 3 |
| 48 | + sleep(2); |
| 49 | + |
| 50 | + % done, exiting will tear down all the threads |
| 51 | + |
| 52 | +end |
| 53 | + |
0 commit comments