特别是在Python中,如何在线程之间共享变量?
虽然我之前使用threading.Thread过,但我从未真正理解或看到变量如何共享的例子.它们是在主线和孩子之间共享还是仅在孩子之间共享?我什么时候需要使用线程本地存储来避免这种共享?
我已经看到很多关于通过使用锁来同步线程间共享数据访问的警告,但我还没有看到问题的一个很好的例子.
提前致谢!
我正在使用Xcode 6.1将现有的Objective-C电视节目应用程序复制到新的Swift版本,并且我在使用CoreData时遇到了一些问题.
我创建了一个包含4个实体的模型,创建了它们的NSManagedObject子类(在Swift中),并且所有文件都设置了适当的应用程序目标(用于"编译源代码").
每当我尝试插入一个新实体时,我仍然会收到此错误:
CoreData:警告:无法为实体"显示"加载名为"显示"的类.找不到类,而是使用默认的NSManagedObject.
一些评论:
保存到Core Data时,我使用父子上下文方式来允许背景线程.我这样做是通过使用以下方法设置ManagedObjectContext:
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
Run Code Online (Sandbox Code Playgroud)
并使用以下方法保存数据:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, …Run Code Online (Sandbox Code Playgroud) 截至2012年2月15日,我还没有找到一个很好的解释,也不知道为什么这不起作用.最接近解决方案的是使用传统的Thread方法,但为什么要包含一个在Android SDK中没有(似乎)工作的类?
Evenin'SO!
我有一个AsyncTask子类:
// ParseListener had a callback which was called when an item was parsed in a
// RSS-xml, but as stated further down it is not used at all right now.
private class xmlAsync extends AsyncTask<String, RSSItem, Void> implements ParseListener
Run Code Online (Sandbox Code Playgroud)
这是这样执行的:
xmlAsync xmlThread = new xmlAsync();
xmlThread.execute("http://www.nothing.com");
Run Code Online (Sandbox Code Playgroud)
现在这个子类遇到了一点错误.以前它做了一些xml-parsing,但是当我注意到它的doInBackground()没有被调用时,我逐行删除它,最后以这样结束:
@Override
protected Void doInBackground(String... params)
{
Log.v(TAG, "doInBackground");
return null;
}
Run Code Online (Sandbox Code Playgroud)
由于某种原因,没有记录任何内容.但是,我补充说:
@Override
protected void onPreExecute()
{
Log.v(TAG, "onPreExecute");
super.onPreExecute();
}
Run Code Online (Sandbox Code Playgroud)
并且在执行线程时确实记录了该行.所以不知何故onPreExecute()被调用但不是doInBackground().我在后台同时运行另一个AsyncTask,效果很好.
我目前正在模拟器上运行应用程序,SDK版本15,Eclipse,Mac …
我有一个运行线程的Android应用程序.我想要一条Toast消息来显示消息.
当我这样做时,我得到以下异常:
Logcat跟踪:
FATAL EXCEPTION: Timer-0
java.lang.RuntimeException: Can't create handler inside thread that has not
called Looper.prepare()
at android.os.Handler.<init>(Handler.java:121)
at android.widget.Toast$TN.<init>(Toast.java:322)
at android.widget.Toast.<init>(Toast.java:91)
at android.widget.Toast.makeText(Toast.java:238)
Run Code Online (Sandbox Code Playgroud)
是否有解决方案将Toast消息从线程推送到用户界面?
我已经沮丧了一段时间,其默认行为ThreadPoolExecutor支持ExecutorService我们这么多人使用的线程池.引用Javadocs:
如果有多个corePoolSize但运行的maximumPoolSize线程少于maximumPoolSize,则只有在队列已满时才会创建新线程.
这意味着如果您使用以下代码定义线程池,它将永远不会启动第二个线程,因为它LinkedBlockingQueue是无限制的.
ExecutorService threadPool =
new ThreadPoolExecutor(1 /*core*/, 50 /*max*/, 60 /*timeout*/,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(/* unlimited queue */));
Run Code Online (Sandbox Code Playgroud)
只有当您有一个有界队列并且队列已满时才会启动核心编号之上的任何线程.我怀疑大量的初级Java多线程程序员并不知道这种行为ThreadPoolExecutor.
现在我有一个特定的用例,这不是最佳的.我正在寻找方法,而不是编写我自己的TPE课程来解决它.
我的要求是针对可能不可靠的第三方回拨的Web服务.
newFixedThreadPool(...)大量的线程,大多数都处于休眠状态.newCachedThreadPool().在更多线程启动之前,如何解决ThreadPoolExecutor队列需要限制和填充的限制?如何让它在排队任务之前启动更多线程?
编辑:
@Flavio提出了使用ThreadPoolExecutor.allowCoreThreadTimeOut(true)核心线程超时并退出的好处.我考虑过这一点,但我仍然想要核心线程功能.如果可能的话,我不希望池中的线程数降到核心大小以下.
使用有什么好处
java.util.concurrent.CountdownLatch
代替
java.util.concurrent.Semaphore?
据我所知,以下片段几乎相同:
1.信号量
final Semaphore sem = new Semaphore(0);
for (int i = 0; i < num_threads; ++ i)
{
Thread t = new Thread() {
public void run()
{
try
{
doStuff();
}
finally
{
sem.release();
}
}
};
t.start();
}
sem.acquire(num_threads);
Run Code Online (Sandbox Code Playgroud)
2:CountDownLatch
final CountDownLatch latch = new CountDownLatch(num_threads);
for (int i = 0; i < num_threads; ++ i)
{
Thread t = new Thread() {
public void run()
{
try
{
doStuff();
}
finally …Run Code Online (Sandbox Code Playgroud) 我听说i ++不是一个线程安全的语句,因为在汇编时它减少了将原始值存储为某个地方的temp,递增它,然后替换它,这可能被上下文切换中断.
但是,我想知道++ i.据我所知,这将减少为单个汇编指令,例如'add r1,r1,1',因为它只有一条指令,所以它不会被上下文切换中断.
任何人都可以澄清吗?我假设正在使用x86平台.
从Rails 4开始,默认情况下,所有内容都必须在线程环境中运行.这意味着所有我们写的代码和 所有我们使用需要是宝石threadsafe
所以,我对此几乎没有问题:
@result ||= some_method?Hash线程安全的?GVL/GIL表示一次只能运行一个红宝石线程,除了IO线程安全变化对我们有影响吗?ruby concurrency multithreading thread-safety ruby-on-rails-4
如何检查哪一个是Swift 3中的当前线程?
在Swift的早期版本中,可以通过执行以下操作来检查当前线程是否是主要线程:
NSThread.isMainThread()
Run Code Online (Sandbox Code Playgroud)