Posted on 2012-12-27 15:15:04 os
OS: ubuntu 12.04 x86_64
GCC: gcc 版本 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <libnotify/notify.h>
void usage(char *);
int close_std();
char * const short_options = "hf:b:";
struct option long_options[] =
{
{"help", 2, NULL, 'h'},
{"file", 2, NULL, 'f'},
{"body", 2, NULL, 'b'},
{NULL, 0, NULL, 0},
};
char * player = "/usr/bin/mplayer";
char * music_file = "/usr/share/sounds/freedesktop/stereo/alarm-clock-elapsed.oga";
char * notify_body = "You have a new mail!";
void usage(char * program_name)
{
printf("%s -h [--help]\n"
"-f [--file=filename] path to music file.\n"
"-b [--body=content] the body of notify dialog.\n", program_name);
exit(1);
}
int close_std()
{
if(close(STDIN_FILENO) == -1 || close(STDOUT_FILENO) ==-1 || close(STDERR_FILENO) == -1)
{
return -1;
}
return 0;
}
int main(int argc, char **argv)
{
int c, pid;
char * program_name = argv[0];
while((c = getopt_long(argc, argv, short_options, long_options, NULL)) != -1)
{
switch(c)
{
case 'h':
usage(program_name);
case 'f':
music_file = optarg;
break;
case 'b':
notify_body = optarg;
break;
case '?':
usage(program_name);
default:
usage(program_name);
}
}
if((close_std() == -1))
{
perror("close_std()");
exit(1);
}
//player music
if((pid = fork()) < 0)
{
perror("fork()");
exit(1);
}
else if(pid == 0)
{
if(execlp(player, player, music_file, (char *)0) < 0)
{
perror("execlp()");
exit(1);
}
exit(0);
}
//send notify information to user
if((pid = fork()) < 0)
{
perror("fork()");
}
else if(pid == 0)
{
notify_init("Mail");
NotifyNotification * notify = notify_notification_new("Mail", notify_body, "Mail");
notify_notification_show(notify, NULL);
exit(0);
}
exit(0);
}
Makefile:
SRC_INCLUDE=-I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/gdk-pixbuf-2.0
CC=gcc
MOD_CFLAGS=-fPIC
CFLAGS=-g -O2 -DHAVE_CONFIG_H -DNSCORE
LDFLAGS=
LIBS=-lnotify
DBG_FLAGS= -DDEBUG=1
OUT_PROGRAM= newmail_notify
all: main
main:
$(CC) $(MOD_CFLAGS) $(CFLAGS) $(SRC_INCLUDE) -o $(OUT_PROGRAM) newmail_notify.c $(MOD_LDFLAGS) $(LDFLAGS) $(LIBS)
Posted on 2012-12-17 17:43:17 tornado
实际代码中使用的是进程池,不过代码很简单,你可以将它替换为线程池。
from time import sleep
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application, asynchronous, RequestHandler
from multiprocessing.pool import ThreadPool
_workers = ThreadPool(10)
def run_background(func, callback, args=(), kwds={}):
def _callback(result):
IOLoop.instance().add_callback(lambda: callback(result))
_workers.apply_async(func, args, kwds, _callback)
def blocking_task(n):
sleep(n)
return n
class Handler(RequestHandler):
@asynchronous
def get(self):
run_background(blocking_task, self.on_complete, (10,))
def on_complete(self, res):
self.write("Test {0}<br/>".format(res))
self.finish()
HTTPServer(Application([("/", Handler)],debug=True)).listen(8888)
IOLoop.instance().start()
Posted on 2012-12-15 01:47:04 python
调用函数时,函数参数仅仅是引用传入对象的名称。
参数传递的基本语义和其他编程语言中已知的方式不完全相同。
例如“按值传递” 或 “按引用传递”。
例如,如果传递不可变的值(如tuple、string list),参数看起来实际是按值传递的。
但如果传递可变变量(如列表或字典)给函数,然后再修改次可变对象,这些改动就会反映在原始对象中。
像这样悄悄修改其输入值或者程序其他部分的函数具有副作用。一般来说,最好避免使用这种编程风格,因为随着程序的规模和复杂度不断增加,这类函数会成为各种奇怪编程错误的来源。(例如,如果函数具有副作用,只看函数调用是无法明显找到问题的。)
在设计线程和并发性的程序中,使用此类函数的效率很低,因为通常需要使用锁定来防止副作用的影响。 多线程环境中,对于每个run函数如果显示修改一个全局变量(一个字典),那么需要为每个线程加锁。 一般的办法就是直接return新变量,而不是“原地修改”
Posted on 2012-12-03 17:37:45 python
首先,在python的线程中,任何在run函数中调用的代码,都是运行在新线程中。
其他的实例方法,全部运行在主线程中。
上代码:
#!/usr/bin/python
# -- coding: utf-8 --
import threading
import signal
import time
# 注意:run函数中执行的代码都是在新线程中
# 而hander方法在主线程中,可以查看它们的thread id
def thread_sig():
# 在子线程中发送信号
signal.alarm(3)
class ihander(threading.Thread):
def __init__(self):
super(ihander, self).__init__()
print threading.currentThread(), " in __init__"
signal.signal(signal.SIGALRM, self.handler)
def run(self):
print threading.currentThread(), " in run"
time.sleep(10)
def handler(self, signum, frame):
print threading.currentThread(), " in handler"
print 'signal: ', signum
h = ihander()
h.start()
t = threading.Thread(target=thread_sig, args=())
t.start()
执行结果:
<_MainThread(MainThread, started 139779179116288)> in __init__
<ihander(Thread-1, started 139779145524992)> in run
<_MainThread(MainThread, stopped 139779179116288)> in handler
signal: 14
我们如果把signal.signal放在其他线程中,就会出错:
def thread_sig():
# 在子线程中发送信号
signal.alarm(3)
signal.signal(signal.SIGALRM, h.handler)
class ihander(threading.Thread):
def __init__(self):
super(ihander, self).__init__()
print threading.currentThread(), " in __init__"
def run(self):
print threading.currentThread(), " in run"
time.sleep(10)
def handler(self, signum, frame):
print threading.currentThread(), " in handler"
print 'signal: ', signum
执行结果是:
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "/data/tornado_analyst/test_signal.py", line 14, in thread_sig
signal.signal(signal.SIGALRM, h.handler)
ValueError: signal only works in main thread
python报告说,signal只能工作在主线程中。
下面是一些关于python中信号的注意点:
/*
NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS
When threads are supported, we want the following semantics:
- only the main thread can set a signal handler
- any thread can get a signal handler
- signals are only delivered to the main thread
I.e. we don't support "synchronous signals" like SIGFPE (catching
this doesn't make much sense in Python anyway) nor do we support
signals as a means of inter-thread communication, since not all
thread implementations support that (at least our thread library
doesn't).
We still have the problem that in some implementations signals
generated by the keyboard (e.g. SIGINT) are delivered to all
threads (e.g. SGI), while in others (e.g. Solaris) such signals are
delivered to one random thread (an intermediate possibility would
be to deliver it to the main thread -- POSIX?). For now, we have
a working implementation that works in all three cases -- the
handler ignores signals if getpid() isn't the same as in the main
thread. XXX This is a hack.
GNU pth is a user-space threading library, and as such, all threads
run within the same process. In this case, if the currently running
thread is not the main_thread, send the signal to the main_thread.
*/
Posted on 2012-12-03 03:06:13 algorithms
摘要:下面是一些比较重要的算法,原文罗列了32个,但我觉得有很多是数论里的,和计算机的不相干,所以没有选取。下面的这些,有的我们经常在用,有的基本不用。有的很常见,有的很偏。不过了解一下也是好事。也欢迎你留下你觉得有意义的算法。(注:本篇文章并非翻译,其中的算法描述大部份摘自Wikipedia,因为维基百科描述的很专业了)
阅读全文Posted on 2012-12-03 03:05:56 life
摘要:我有两个朋友。
L的公司在上海,大半时间跑广东。他是华南某所不太知名的大学毕业的,小眼睛质朴男,多年以前还是个文学青年。哥们做手机网游的,我见他使过好几款手机, 但最贵的一个也不过1千多块钱。比起什么Web2.0、移动互联网的概念,他更关心珠三角的几千万农民工和城市边缘的大学生“蚁族”,怎么关心?在东莞的 夜宵摊上跟他们拼啤酒,在富士康厂区外网吧里刷夜,跟靠做他们生意开上宝马的便利店老板扯淡……
阅读全文Posted on 2012-12-03 01:31:13 life
欲先为贼;利先为贩;义先为商!
善己者为奴,善伴者为工,善众者为商!
羡鱼者终穷,羡渔者终饱,羡网者终富!
奴者多怨,工者多思,商者多行!
嗜蜜者多盗,品苦者多商!
三四者为奴,一一者为商!
滥情者为奴,多情者为工,寡情者为商!
小贩:嗜蜜、好群、意淫、尚奢
巨商:品苦、喜独、意精、知俭