举例说明怎么简单的创建一个子线程


用到的类是NSThread类,这里使用detachNewTheadSelector:toTagaet:withObject创建一个线程。

函数setupThread:(NSArray*)userInfor。通过userInfor将需要的数据传到线程中。

函数定义:

-(void)setupThread:(NSArray*)userInfor{

   [NSThread detachNewThreadSelector:@selector(threadFunc:) toTarget:self withObject:(id)userInfor];

}

- (void)threadFunc:(id)userInfor{

   NSAutoreleasePool*pool = [[NSAutoreleasePool alloc] init];

   //。。。。需要做的处理。

   //这里线程结束后立即返回

  [self performSelectorOnMainThread:@selector(endThread) withObject:nil waitUntilDone:NO];

  [pool release];

}

performSelectorOnMainThread通知主线程执行函数endThread。也可以使用performSelector:onThread:withObject:waitUntil 通知某线程执行线程结束后的处理。

线程内不要刷新界面。如果需要刷新界面,通过performSelectorOnMainThread,调出主线程中的方法去刷新。

 

例如,启动一个线程下载图片:

//启动线程

[NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:url];

//线程函数

- (void) downloadImage:(NSString*)url{
    
    _subThreed = [NSThread currentThread];
    
    self.uploadPool = [[NSAutoreleasePool alloc] init];
    self.characterBuffer = [NSMutableData data];
    done = NO;
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURLURLWithString:url]];
    
    self.connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    [self performSelectorOnMainThread:@selector(httpConnectStart) withObject:nil waitUntilDone:NO];
    if (connection != nil) {
        do {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        } while (!done);
    }
    
    self.photo = [UIImage imageWithData:characterBuffer];
    

    //下载结束,刷新
    [self performSelectorOnMainThread:@selector(fillPhoto) withObject:nil waitUntilDone:NO];
    
    // Release resources used only in this thread.
    self.connection = nil;
    [uploadPool release];
    self.uploadPool = nil;
    
    _subThreed = nil;
}


#pragma mark NSURLConnection Delegate methods

/*
 Disable caching so that each time we run this app we are starting with a clean slate. You may not want to do this in your application.
 */

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {

    return nil;
}

// Forward errors to the delegate.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    done = YES;
    [self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil waitUntilDone:NO];
    [characterBuffer setLength:0];
    
}

// Called when a chunk of data has been downloaded.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Process the downloaded chunk of data.
 
    [characterBuffer appendData:data];
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    
    [self performSelectorOnMainThread:@selector(httpConnectEnd) withObject:nil waitUntilDone:NO];
    // Set the condition which ends the run loop.
    done = YES; 
}


线程池是一种常见的并发工具,它可以有效地管理多个线程,提高程序性能并避免频繁地创建和销毁线程所导致的开销。在C++中,我们可以使用`std::thread_pool`(如果它是STL的一部分,但标准库并没有提供这个接口)或自定义实现来创建线程池。 以下是一个简单的自定义线程池示例,使用`std::vector`存储线程,以及一个条件变量和互斥锁来确保线程安全: ```cpp #include <vector> #include <condition_variable> #include <mutex> #include <future> class ThreadPool { public: ThreadPool(size_t thread_count) : stopped(false), threads(thread_count) { for (size_t i = 0; i < thread_count; ++i) { threads[i] = std::thread([this] { worker(); }); } } ~ThreadPool() { // 设置停止标志,然后等待所有任务完成 stop(); join_threads(); } template<typename Func, typename... Args> auto enqueue(Func&& func, Args&&... args) -> std::future<decltype(func(args...))> { std::lock_guard<std::mutex> lock(queue_mutex); tasks.emplace_back(std::move(func), std::forward<Args>(args)...); condition.notify_one(); return task_results.front(); } private: void worker() { while (!stopped) { std::unique_lock<std::mutex> lock(queue_mutex); condition.wait(lock, [this] { return !tasks.empty() || stopped; }); if (!tasks.empty()) { std::packaged_task<decltype(tasks.back().first)> task = tasks.front(); tasks.pop_front(); try { task.call_soon(); } catch (...) { // Handle exceptions in the background } } } } void stop() { stopped = true; condition.notify_all(); } void join_threads() { for (auto& t : threads) { if (t.joinable()) { t.join(); } } } std::vector<std::thread> threads; std::queue<std::packaged_task<decltype(tasks.back().first)>> tasks; std::mutex queue_mutex; std::condition_variable condition; std::deque<std::future<decltype(tasks.back().first)>> task_results; // For returning results }; // 示例用法 int main() { ThreadPool pool(4); for (int i = 0; i < 10; ++i) { pool.enqueue([](int n) { std::cout << "Task " << n << " started by thread " << std::this_thread::get_id() << '\n'; }, i); } // 所有任务完成后,线程池自动关闭 return 0; } ``` 在这个例中,我们创建了一个线程池,当有新的任务(`enqueue`方法中的函数)加入时,会在队列中等待处理。当一个线程空闲时,它会从队列中取出一个任务执行。 线程池的安全主要体现在对任务队列的访问上,通过`std::mutex`和`std::condition_variable`保证了多线程环境下的线程同步。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值