我正在寻找实现以下内容的最简单,最直接的方法:
n同时运行任务.n到达,没有更多的工人开始,直到运行的线程数降回到低于n.我正在学习pthread和等待条件.据我所知,一个典型的等待线程是这样的:
pthread_mutex_lock(&m);
while(!condition)
pthread_cond_wait(&cond, &m);
// Thread stuff here
pthread_mutex_unlock(&m);
Run Code Online (Sandbox Code Playgroud)
我无法理解的是,while(!condition)即使我pthread_cond_signal()用来唤醒线程,为什么这条线是必要的.
我可以理解,如果我使用pthread_cond_broadcast()我需要测试条件,因为我唤醒所有等待的线程,其中一个可以在解锁互斥锁之前再次使条件为假(从而将执行转移到另一个不应该执行的唤醒线程点).但是,如果我使用pthread_cond_signal()我只唤醒一个线程,所以条件必须是真的.所以代码看起来像这样:
pthread_mutex_lock(&m);
pthread_cond_wait(&cond, &m);
// Thread stuff here
pthread_mutex_unlock(&m);
Run Code Online (Sandbox Code Playgroud)
我读到了一些可能发生的虚假信号.这是(也是唯一的)原因吗?我为什么要有虚假的信号呢?或者还有其他我没有得到的东西?
我假设信号代码是这样的:
pthread_mutex_lock(&m);
condition = true;
pthread_cond_signal(&cond); // Should wake up *one* thread
pthread_mutex_unlock(&m);
Run Code Online (Sandbox Code Playgroud) Dispatcher当你没有引用任何UI元素时,有没有办法获得UI线程?
以下是实现相当简单的线程安全日志记录类的正确方法吗?
我知道我从未明确关闭过TextWriter,这会是一个问题吗?
当我最初使用该TextWriter.Synchronized方法时,它似乎没有工作,直到我在静态构造函数中初始化它并使它只读它:
public static class Logger
{
static readonly TextWriter tw;
static Logger()
{
tw = TextWriter.Synchronized(File.AppendText(SPath() + "\\Log.txt"));
}
public static string SPath()
{
return ConfigManager.GetAppSetting("logPath");
}
public static void Write(string logMessage)
{
try
{
Log(logMessage, tw);
}
catch (IOException e)
{
tw.Close();
}
}
public static void Log(string logMessage, TextWriter w)
{
w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
w.WriteLine(" :");
w.WriteLine(" :{0}", logMessage);
w.WriteLine("-------------------------------");
// Update the underlying file.
w.Flush();
}
}
Run Code Online (Sandbox Code Playgroud) 我在Tomcat上运行Web应用程序.我有一个处理所有数据库查询的类.此类包含Connection返回查询结果的对象和方法.
这是连接对象:
private static Connection conn = null;
Run Code Online (Sandbox Code Playgroud)
它只有一个实例(单例).
另外,我有执行查询的方法,例如在db中搜索用户:
public static ResultSet searchUser(String user, String pass) throws SQLException
Run Code Online (Sandbox Code Playgroud)
此方法使用静态Connection对象.我的问题是,我在静态Connection对象线程中的使用是否安全?或者当很多用户调用该searchUser方法时会引起问题吗?
我一直试图解决这个崩溃将近一个星期.应用程序崩溃,没有任何异常或堆栈跟踪.在僵尸模式下运行仪器时,应用程序不会以任何方式崩溃.
我有一个在不同的线程上调用的方法.修复崩溃的解决方案正在取代
[self.mutableArray removeAllObjects];
Run Code Online (Sandbox Code Playgroud)
同
dispatch_async(dispatch_get_main_queue(), ^{
[self.searchResult removeAllObjects];
});
Run Code Online (Sandbox Code Playgroud)
我认为这可能是一个时间问题,所以我尝试同步它,但它仍然崩溃:
@synchronized(self)
{
[self.searchResult removeAllObjects];
}
Run Code Online (Sandbox Code Playgroud)
这是代码
- (void)populateItems
{
// Cancel if already exists
[self.searchThread cancel];
self.searchThread = [[NSThread alloc] initWithTarget:self
selector:@selector(populateItemsinBackground)
object:nil];
[self.searchThread start];
}
- (void)populateItemsinBackground
{
@autoreleasepool
{
if ([[NSThread currentThread] isCancelled])
[NSThread exit];
[self.mutableArray removeAllObjects];
// Populate data here into mutable array
for (loop here)
{
if ([[NSThread currentThread] isCancelled])
[NSThread exit];
// Add items to mutableArray
}
}
}
Run Code Online (Sandbox Code Playgroud)
NSMutableArray的这个问题不是线程安全的吗?
我正在尝试在python中创建多线程Web服务器,但它一次只响应一个请求,我无法弄清楚原因.你能帮我吗?
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
from time import sleep
class ThreadingServer(ThreadingMixIn, HTTPServer):
pass
class RequestHandler(SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
sleep(5)
response = 'Slept for 5 seconds..'
self.send_header('Content-length', len(response))
self.end_headers()
self.wfile.write(response)
ThreadingServer(('', 8000), RequestHandler).serve_forever()
Run Code Online (Sandbox Code Playgroud) 我已经在这里阅读过以前的问题,ConcurrentBag但没有找到多线程实现的实际示例.
ConcurrentBag是一个线程安全的包实现,针对同一个线程生成和使用存储在包中的数据的情况进行了优化.
目前这是我的代码中的当前用法(这是简化而非实际代码):
private void MyMethod()
{
List<Product> products = GetAllProducts(); // Get list of products
ConcurrentBag<Product> myBag = new ConcurrentBag<Product>();
//products were simply added here in the ConcurrentBag to simplify the code
//actual code process each product before adding in the bag
Parallel.ForEach(
products,
new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
product => myBag.Add(product));
ProcessBag(myBag); // method to process each items in the concurrentbag
}
Run Code Online (Sandbox Code Playgroud)
我的问题:
这是正确的用法ConcurrentBag吗?ConcurrentBag在这种情况下可以使用吗?
对我来说,我认为一个简单List<Product>的手动锁会做得更好.这样做的原因是上面的场景已经打破了" 同一个线程将生成和消费存储在包中的数据 "规则.
另外我还发现 …
在heroku dyno的背景下,美洲狮工人和美洲狮线程有什么区别?
我所知道的(如果我错了,请纠正我):
精简不是并发的,因此Web进程一次只能执行一个请求
在独角兽中,我知道我可以在一个进程中有几个unicorn worker来添加并发性.
但在美洲狮有线程和工人..在美洲狮过程中,工人不是一个线程吗?
我可以在Heroku中使用更多的worker/threads来添加web并发吗?
multithreading ×10
c# ×2
concurrency ×2
java ×2
python ×2
c ×1
connection ×1
dispatcher ×1
heroku ×1
http ×1
ios ×1
jdbc ×1
logging ×1
objective-c ×1
pthreads ×1
puma ×1
servlets ×1
webserver ×1
wpf ×1